Entity Framework CodeFirst many to many relationship with additional information

前端 未结 2 1896
無奈伤痛
無奈伤痛 2020-12-02 18:50

I have the following model :

class Contract
{
   string ContractID{get;set;}
   ICollection Parts{get;set;}
}

class Part
{
   string PartID{get;         


        
相关标签:
2条回答
  • 2020-12-02 19:32

    In such case you must model your entities this way:

    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
    }
    

    In derived context you must define:

    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);  
    }
    
    0 讨论(0)
  • 2020-12-02 19:35

    Perhaps a better way to do is this answer? Create code first, many to many, with additional fields in association table

    It doesn't require fluent APIs and also sets up the PK on join table.

    0 讨论(0)
提交回复
热议问题