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

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

问题描述

下面是这样,我有2个实体,如合同,媒体。

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 has many Medias, it seems that they are many to many.

但是!在EF code首先,我需要在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.

在你情况下,它将是:

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 ICollection<Media> Medias { get; set; }
    public virtual ICollection<Contract> Contracts { 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);  
}

您也可以参考以下链接:

<一href=\"http://stackoverflow.com/questions/15153390/many-to-many-mapping-with-extra-fields-in-fluent-api\">Many许多映射用流利的API
<一href=\"http://stackoverflow.com/questions/5434125/entity-framework-$c$cfirst-many-to-many-relationship-with-additional-information\">Entity框架codeFirst多对多的关系与其他信息

<一href=\"http://stackoverflow.com/questions/7050404/create-$c$c-first-many-to-many-with-additional-fields-in-association-table\">Create code首先,多对多,与关联表的附加字段

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

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