我正在尝试使用Fluent API在实体框架核心中创建多对多关系这是我的第一个型号:
MyCalculationSelector.cs
public int SortOrder { get; set; }
public string UserString { get { return Name; } }
private IList<CalculationType> _calculationTypes;
public virtual IList<CalculationType> CalculationTypes
{
get { return _calculationTypes; }
set { _calculationTypes = value; }
}
这是我的第二个型号:
MyCalculationType.cs
public int SortOrder { get; set; }
public string UserString
{
get { return Name; }
}
public int CalculationMethod { get; set; }
我记得EF 6可以很容易地建立Fluent API的多对多关系:
modelBuilder.Entity<MyCalculationSelector>().HasMany(x => x.MyCalculationTypes).WithMany();
我们能在ef核心中实现这样的目标吗?到目前为止,Hasmany-Withmany实现是不可能的
您可以用私有字段或属性表示:
modelBuilder.Entity<MyCalculationSelector>()
.HasMany(x => x.MyCalculationTypes)
.WithMany("NameOfThePrivateFieldOnMyCalculationType");
这样,导航属性就不会公开,但您仍然可以在MyCalculationSelector
上使用导航属性,而无需遍历中间联接表。
我遵循了文档并给出了这个答案,请比我了解更多的人,如果我错了,他会纠正我。
我首先创建了我的联接表:
CalculationSelectorCalculationType.cs
public class CalculationSelectorCalculationType
{
public int CalculationSelector_Id { get; set; }
public CalculationSelector CalculationSelector { get; set; }
public int CalculationType_Id { get; set; }
public CalculationType CalculationType { get; set; }
}
CalculationSelector.cs
public CalculationSelector()
{
_calculationTypes = new List<CalculationSelectorCalculationType>();
FontSize = 30;
}
public int SortOrder { get; set; }
public string UserString { get { return Name; } }
private IList<CalculationSelectorCalculationType> _calculationTypes;
public virtual IList<CalculationSelectorCalculationType> CalculationTypes
{
get { return _calculationTypes; }
set { _calculationTypes = value; }
}
CalculationType.cs
public int SortOrder { get; set; }
public string UserString
{
get { return Name; }
}
public int CalculationMethod { get; set; }
最后是我的DbContext:
modelBuilder.Entity<CalculationSelectorCalculationType>().HasKey(p => new { p.CalculationSelector_Id, p.CalculationType_Id });
modelBuilder.Entity<CalculationSelectorCalculationType>().HasOne(p => p.CalculationSelector).WithMany(x => x.CalculationTypes).HasForeignKey(p => p.CalculationSelector_Id);
modelBuilder.Entity<CalculationSelectorCalculationType>().HasOne(p => p.CalculationType).WithMany().HasForeignKey(p => p.CalculationType_Id);