实体框架代码首先与其他信息建立多对多的关系

时间:2011-03-25 14:52:58

标签: c# .net entity-framework ef-code-first entity-framework-4.1

我有以下型号:

class Contract
{
   string ContractID{get;set;}
   ICollection<Part> Parts{get;set;}
}

class Part
{
   string PartID{get;set;}
   ICollection<Contract> Contracts{get;set;}
}

问题是Part和Contract之间的关系还包含以下附加信息:

class ContractParts
{ 
   Contract{get;set;}
   Part{get;set;}
   Date{get;set;} //additional info
   Price{get;set;} //additional info
}

我如何为此编写实体上下文?

2 个答案:

答案 0 :(得分:41)

在这种情况下,您必须以这种方式为实体建模:

public class Contract
{
   public virtual string ContractId { get; set; }
   public virtual ICollection<ContractPart> ContractParts { get; set; }
}

public class Part
{
   public virtual string PartId { get;set; }
   public virtual ICollection<ContractPart> ContractParts { get; set; }
}

public class ContractPart
{ 
   public virtual string  ContractId { get; set; }
   public virtual string PartId { get; set; }
   public virtual Contract Contract { get; set; }
   public virtual Part Part { get; set; }
   public virtual string Date { get; set; } //additional info
   public virtual decimal Price { get; set; } //additional info
}

在派生上下文中,您必须定义:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<ContractPart>()
               .HasKey(cp => new { cp.ContractId, cp.PartId });

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

   modelBuilder.Entity<Part>()
               .HasMany(p => p.ContractParts)
               .WithRequired()
               .HasForeignKey(cp => cp.PartId);  
}

答案 1 :(得分:5)

或许更好的方法是这个答案? Create code first, many to many, with additional fields in association table

它不需要流畅的API,也可以在连接表上设置PK。