EF Core:无需导航即可映射多对多关系 属性

EF Core: Map Many to Many relationship without navigation property

我正在尝试使用 Fluent API 在 entity Framework Core 中创建多对多关系 这是我的第一个模型:

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 core 中实现这样的功能吗?截至今天,Hasmany-Withmany 实施是不可能的

我已经按照文档得出了这个答案,请比我更了解的人,如果我错了,请纠正我。

我首先创建了我的连接 table:

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);

您可以用私有字段或 属性:

表示
modelBuilder.Entity<MyCalculationSelector>()
    .HasMany(x => x.MyCalculationTypes)
    .WithMany("NameOfThePrivateFieldOnMyCalculationType");

这样导航 属性 不会公开,但您仍然可以在 MyCalculationSelector 上使用导航 属性 而无需遍历中间连接 table。