我最近来上课ManyNavigationPropertyConfiguration<TEntity, TTarget>
,并且在该类中我找到了一个名为 WithMany()
的方法有 2 个重载。
第一次重载:
WithMany()
Configures the relationship to be many:many without a navigation property on the other side of the relationship.
第二次重载:
WithMany(Expression<Func<TTarget, ICollection<TEntity>>>)
Configures the relationship to be many:many with a navigation property on the other side of the relationship.
现在我的问题是,为什么要将关系配置为 many:many 而没有导航属性(第一个重载)?我看不到任何有用的场景……有什么想法吗?
最佳答案
一个例子可能是这个模型:
public class User
{
public int UserId { get; set; }
public string Name { get; set; }
public ICollection<Role> Roles { get; set; }
}
public class Role
{
public int RoleId { get; set; }
public string Description { get; set; }
}
如果您永远不想检索处于特定角色的所有用户,添加一个导航属性...
public ICollection<User> Users { get; set; }
... Role
类将是不必要的开销。
但您仍然必须通过 EF 告知 User
和 Role
之间存在多对多关系...
modelBuilder.Entity<User>()
.HasMany(u => u.Roles)
.WithMany();
...因为默认约定映射会创建错误的关系,即一对多关系,对应于此映射:
modelBuilder.Entity<User>()
.HasMany(u => u.Roles)
.WithOptional();
关于c# - EF 代码优先 - WithMany(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5927272/