如何在Entity Framework Core的多个字段中创建多对多关系

时间:2019-06-26 09:32:01

标签: entity-framework entity-framework-core

如何在实体框架核心中创建与多个字段具有多对多关系的表?

我尝试使用efcore在数据库中创建多对多关系,但是如果有多个字段,我就会遇到问题。

public class Sheet{
 [Key]
 public long Id{get;set;}
 public virtual ICollection<SheetBudgetMonth> firstbudgetMonth = new List<SheetBudgetMonth>();
public virtual ICollection<SheetBudgetMonth> secondbudgetMonth = new List<SheetBudgetMonth>();
public virtual ICollection<SheetBudgetMonth> thirdbudgetMonth = new List<SheetBudgetMonth>();
}

public class SheetBudgetMonth{
 public long SheetId {get;set;}
 public virtual Sheet Sheet{get;set;}
 public long BudgetMonthId {get;set;}
 public virtual BudgetMonth BudgetMonth{get;set;}
}

public class BudgetMonth{
 [Key]
 public long Id{get;set;}

 public string Code{get;set;}

 public DateTime BudgetDate{get;set;}
}

//many to many link table mappings
modelBuilder.Entity<SheetBudgetMonth>().HasKey(bc=>{bc.SheetId, bc.BudgetMonthId});

modelBuilder.Entity<SheetBudgetMonth>().HasOne(bc => bc.Sheet).WithMany(b => b.firstbudgetMonth ).HasForeignKey(bc => bc.SheetId);

modelBuilder.Entity<SheetBudgetMonth>().HasOne(bc => bc.Sheet).WithMany(b => b.secondbudgetMonth ).HasForeignKey(bc => bc.SheetId);

modelBuilder.Entity<SheetBudgetMonth>().HasOne(bc => bc.Sheet).WithMany(b => b.thirdbudgetMonth ).HasForeignKey(bc => bc.SheetId);

Migraton抛出一条错误消息,指出“ firstbudgetMonth和电子表格之间已经存在关系。”导航属性只能参与单个关系。

0 个答案:

没有答案