c# - EF 代码优先 - WithMany()

标签 c# entity-framework ef-code-first

我最近来上课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 告知 UserRole 之间存在多对多关系...

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/

相关文章:

c# - 仅限 EF 4.1 代码?

c# - 第二个 WPF 窗口为空白

entity-framework - Sql Azure 的暂时性错误

.net - EF4.1 Code First 复杂类型作为主键

c# - 带有 EF6 的 System.data.Sqlite

c# - 重新使用继承的 FK 关系?

sql-server-express - 在 Visual Studio 中安装/连接后连接到 SQL Server Express 的 Entity Framework 错误

c# - 调用 Web 服务异步

c# - 无法正确导航到 Selenium webDriver 2.0b3 IE 和 chrome 中的 url

c# - 按月将一个列表拆分为多个 - C#、Linq