如何在实体框架中创建多对多映射? [英] How to create a many-to-many mapping in Entity Framework?

查看:23
本文介绍了如何在实体框架中创建多对多映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是这样的,我有2个实体,比如Contract、Media.

Here is the case, I have 2 entities, such as Contract、Media。

public class Media : Entity
{
    public string Name {get; set;}
    public bool Enabled
    *//other properties can be ignored..*
}

public class Contract : Entity
{
    public string Code {get; set;}
    *//other properties can be ignored..*
}

Contract 有很多 Medias,好像是多对多.

Contract has many Medias, it seems that they are many to many.

但是!!首先在 ef 代码中,我需要 ContractMedia 表中的另外 3 个字段(ef 自动生成).例如开始日期、结束日期和价格.这些无法添加到媒体实体中.

在这种情况下如何映射??

How to map at this case??

推荐答案

如果要与关联表中的附加数据创建多对多关系,则必须将关联表作为实体.纯多对多关系只存在于带有实体id的纯表中.

If you want to create many to many relationship with additional data in association table, you have to make the association table as entity. The pure many to many relationship is only in pure table with entity id's.

在你的情况下,它将是:

In you case it will be:

public class Media // One entity table
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool Enabled { get; set; }

    public virtual ICollection<ContractMedia> ContractMedias { get; set; }
}

public class Contract // Second entity table
{
    public int Id { get; set; }
    public string Code { get; set }

    public virtual ICollection<ContractMedia> ContractMedias { get; set; }
}

public class ContractMedia // Association table implemented as entity
{
    public int MediaId { get; set; }
    public int ContractId { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public double Price { get; set; }

    public virtual Media Media { get; set; }
    public virtual Contract Contract { get; set; }
}

在创建模型/实体之后,您需要在上下文中定义关系:

And after you created models/entities, you need to define relationships in context:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<ContractMedia>()
       .HasKey(c => new { c.MediaId, c.ContractId });

   modelBuilder.Entity<Contract>()
       .HasMany(c => c.ContractMedias)
       .WithRequired()
       .HasForeignKey(c => c.ContractId);

   modelBuilder.Entity<Media>()
       .HasMany(c => c.ContractMedias)
       .WithRequired()
       .HasForeignKey(c => c.MediaId);  
}

您也可以参考以下链接:
Fluent API 中带有额外字段的多对多映射
实体框架 CodeFirst 多对多关系与附加信息
先创建代码,多对多,与关联表中的附加字段

Also you can refer to these links:
Many to many mapping with extra fields in Fluent API
Entity Framework CodeFirst many to many relationship with additional information
Create code first, many to many, with additional fields in association table

这篇关于如何在实体框架中创建多对多映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆