简体   繁体   English

如何使用Entity Framework在c#中访问多对多映射表

[英]How to access many to many mapped table in c# with Entity Framework

I am using EF code-first. 我先使用EF代码。 I have two classes Users and Roles which are mapped in a many-to-many relationship as below. 我有两个类“ Users和“ Roles ,它们以多对多关系映射,如下所示。

public class User
{
    public User()
    {
        this.Roles = new HashSet<Role>();
    }

    public int UserId { get; set; }
    public string UserName { get; set; }
    public string PasswordHash { get; set; }
    public DateTime? LastLoggedOn { get; set; }
    public DateTime? PasswordChangedOn { get; set; }
    public int IsActive { get; set; }

    public virtual ICollection<Role> Roles { get; set; }
}

public class Role
{
    public Role()
    {
        this.Users = new HashSet<User>();
    }

    public int RoleId { get; set; }
    public string RoleName { get; set; }
    public string Description { get; set; }

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

public class UserMap : EntityTypeConfiguration<User>
{
    public UserMap()
    {
        HasMany(r => r.Roles).WithMany(u=>u.Users)
            .Map(m =>
            {
                m.ToTable("UserRoles");
                m.MapLeftKey("UserId");
                m.MapRightKey("RoleId");
            });
    }
}

Now I want to fetch RoleName from Roles with respective to UserId from Users 现在我想从Roles RoleName分别从Users获取到UserId

I am using this code: 我正在使用此代码:

var roleName = db.Users.Join(db.UserRoles, u => u.UserId, r => r.UserId, (u, r) => new { u, r })
                       .Join(db.Roles, ur => ur.r.RoleId, q => q.RoleId, (ur, q) => new { ur, q })
                       .Where(m => m.ur.r.UserId == 1)
                       .Select(m => new { m.ur.r.UserId, m.q.RoleName });

But it does not allow me to use UserRoles . 但是它不允许我使用UserRoles

Error 错误

'Context' does not contain a definition for 'UserRoles' and no extension method 'UserRoles' accepting a first argument of type 'Context' could be found (are you missing a using directive or an assembly reference?) “上下文”不包含“ UserRoles”的定义,找不到可以接受类型为“ Context”的第一个参数的扩展方法“ UserRoles”(是否缺少using指令或程序集引用?)

Can anyone help me here? 有人能帮我一下吗?

The name of the table you define in the fluent API will only be used (and known) by the database. 您在fluent API中定义的表的名称将仅由数据库使用(并且已知)。 From your application, you should query it by doing : 在您的应用程序中,您应该执行以下操作来查询它:

db.Users.Find(userId).SelectMany(x=>x.Roles).SelectMany(x=>x.RoleName)

Note that this will load all Roles from the user in memory, but this is fine since you will never have 1000 roles for one user I guess. 请注意,这会从用户的内存中加载所有角色,但这很好,因为我猜您永远不会为一个用户拥有1000个角色。

Apart from that, I think that you should only have a 1 to 1 relationship between Roles and Users. 除此之外,我认为角色和用户之间应该只有一对一的关系。 I'd advise to add a UserId column in the role class and to remove the Users collection from this class. 我建议在角色类中添加UserId列,并从此类中删除Users集合。

This way, your query will simply be : 这样,您的查询将简单地是:

db.Roles.Where( x => x.UserId = userId).Select( x => x.RoleName);

And this time, only the Role Names will be pulled into memory. 这次,只有角色名称将被拉入内存。 I think it is also a slightly better design. 我认为这也是一个更好的设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C#实体框架添加到多对多表 - C# Entity Framework Adding to Many-To-Many Table C#中的实体框架一对多关系 - Entity framework one to many relationship in C# 代码优先实体框架C#,多对多映射,创建连接表,但未在对象上填充列表属性 - Code First Entity Framework C#, Many to Many Mapping, Junction Table Created but list property not populated on object C#实体框架5多对多查看数据 - C# Entity Framework 5 many to many viewing data C# - 实体框架核心 - 多对多关系错误 - C# - Entity Framework Core - Many to Many relation error C#实体框架与数量的多对多关系 - C# Entity Framework many-to-many relationship with quantity 如何通过实体框架访问多对多表? asp.net - How to access many-to-many table via Entity Framework? asp.net ASP .NET Core MVC Entity Framework - 如何访问由多对多关系产生的表? - ASP .NET Core MVC Entity Framework - How to get access to a table which is result of many-to-many relationship? 如何使用实体框架在C#中的多对多关系上运行linq查询 - How to run linq query on many-to-many relationship in c# with entity framework 实体框架-如何插入具有附加属性的多对多表? - Entity framework - how to insert into many to many table with additional properties?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM