【发布时间】:2021-10-07 14:49:31
【问题描述】:
我已经使用以下代码配置了我的 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);
}
问题是我不希望Role 实体持有Users 的集合。我保留它是因为 EF Core 需要它来配置多对多关系。
有没有办法创建相同的关系,但不必定义Role.Users 导航属性?
【问题讨论】:
-
看起来这可能是不可能的,但在这里提交和跟踪作为增强:github.com/dotnet/efcore/issues/3864
-
如果您绝对想要阻止
Role了解用户,那么您必须通过使用显式联结类来解决问题。但这不是你要问的,所以我不认为这是一个答案。
标签: c# .net entity-framework-core many-to-many navigation-properties