EF代码优先 - WithMany() [英] EF Code First - WithMany()

查看:1665
本文介绍了EF代码优先 - WithMany()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我由类 ManyNavigationPropertyConfiguration< TEntity,TTarget>
,那班上有中,我发现了一个名为方法 WithMany ()与2重载

I recently came by the class ManyNavigationPropertyConfiguration<TEntity, TTarget> , and within that class there I found a method named WithMany() with 2 overloads.

第一个过载:
WithMany()

配置的关系为
许多:许多不上的另一侧的导航
属性
的关系。

Configures the relationship to be many:many without a navigation property on the other side of the relationship.

第二个重载:
WithMany(表达式来; Func键< TTarget ,ICollection的< TEntity>>>)

配置的关系是
多方面的:多用在关系的另一端的导航属性

Configures the relationship to be many:many with a navigation property on the other side of the relationship.

现在是我的问题,你为什么会配置关系是多方面的:许多人没有导航属性(第一个过载)?我没有看到任何场景中,这将是有益的...任何想法

Now is my question, why would you configure a relationship to be many:many without a navigation property (the first overload)? I dont see any scenarios where that would be helpful... Any thoughts?

推荐答案

一个例子可能是这种模式:

An example might be this model:

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

如果你永远不会有兴趣来获取这是在所有用户特定角色后,加入了导航属性...

If you are never interested to retrieve all users which are in a specific role, adding a navigation property ...

public ICollection<User> Users { get; set; }



...到角色类是不必要的开销。

但你还是必须EF告诉一个多到很多用户之间的关系角色存在...

But you still must EF tell that a many-to-many relationship between User and Role exists ...

modelBuilder.Entity<User>()
            .HasMany(u => u.Roles)
            .WithMany();



...因为默认公约映射将产生一个错误的关系,即一对多关系,对应的映射:

... because the default convention mappings would create a wrong relationship, namely a one-to-many relationship, corresponding to this mapping:

modelBuilder.Entity<User>()
            .HasMany(u => u.Roles)
            .WithOptional();

这篇关于EF代码优先 - WithMany()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆