在这种情况下,我有2个实体,例如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)有许多媒体,看来它们是多对多的。

但是!首先在EF代码,我需要在ContractMedia表(EF自动生成)中再添加3个字段。
例如StartDate,EndDate和Price。无法将其添加到媒体实体中。


在这种情况下如何映射?

最佳答案

如果要使用关联表中的其他数据创建多对多关系,则必须将关联表作为实体。纯多对多关系仅在具有实体ID的纯表中。

在您的情况下,它将是:

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; }
}

创建模型/实体后,需要在上下文中定义关系:
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);
}

您也可以引用以下链接:
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

关于c# - 如何在 Entity Framework 中创建多对多映射?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19342908/

10-12 05:07