我试图首先在EF代码中建立多对多关系,但默认约定是错误的.以下类描述了这种关系:
class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
class Account
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
一个帐户可以有许多产品.
但是,EF约定将创建DB表,如下所示:
Products Table
--------------
Id
Name
Account_Id <- What is this?
Accounts Table
--------------
Id
Name
Run Code Online (Sandbox Code Playgroud)
这看起来不像是一个多对多的表结构?如何配置流畅的API以反映关系并创建中间表:
AccountProducts Table
---------------------
Account_Id
Product_Id
Run Code Online (Sandbox Code Playgroud) 我已经使用以下代码配置了我的 DbContext(EF Core 5.0):
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(p => p.Roles)
.WithMany(p => p.Users)
.UsingEntity<Dictionary<string, object>>("UsersToRoles",
x => x.HasOne<Role>().WithMany().HasForeignKey("UserId"),
x => x.HasOne<User>().WithMany().HasForeignKey("UserId"),
x => x.ToTable("UsersToRoles"));
modelBuilder.Entity<Role>()
.ToTable("Roles")
.Property(r => r.Application)
.IsRequired();
base.OnModelCreating(modelBuilder);
}
Run Code Online (Sandbox Code Playgroud)
问题是我不希望Role实体持有Users. 我保留它是因为 EF Core 需要它来配置多对多关系。
有没有办法创建相同的关系,但不必定义Role.Users导航属性?
.net c# many-to-many navigation-properties entity-framework-core