Entity Framework CodeFirst многие ко многим отношения с дополнительной информацией - PullRequest
26 голосов
/ 25 марта 2011

У меня есть следующая модель:

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

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

Проблема в том, что отношения между Частью и Контрактом также содержат следующую дополнительную информацию:

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

Как бы я написал контекст сущности для этого?

Ответы [ 2 ]

41 голосов
/ 25 марта 2011

В таком случае вы должны смоделировать свои сущности следующим образом:

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);  
}
5 голосов
/ 07 декабря 2012

Возможно, лучший ответ - это ответ? Сначала создайте код, многие ко многим, с дополнительными полями в таблице ассоциаций

Не требует свободных API, а также устанавливает PK в таблице соединений.

...