实体框架codeFirst许多与其他信息一对多的关系 [英] Entity Framework CodeFirst many to many relationship with additional information

查看:172
本文介绍了实体框架codeFirst许多与其他信息一对多的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:

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

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

问题是,部分与合同之间的关系还包含以下附加信息:

the problem is that the relationship between Part and Contract also contains the following additional information :

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

我怎么会写实体语境呢?

How would I write the Entity Context for this ?

推荐答案

在这种情况下,你必须符合您的实体是这样的:

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 OnModelCreateing(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);  
}

这篇关于实体框架codeFirst许多与其他信息一对多的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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