【问题标题】:Join EF code first many to many relationship tables首先加入 EF 代码多对多关系表
【发布时间】:2014-04-28 23:22:03
【问题描述】:

我正在开发一个 asp.net mvc5 ef5 应用程序。我使用 ef 代码优先方法。我有两个表 User(UserId,Name) 和 Role(RoleId, Name)。我的 DataContext 类看起来像这样:

using System.Data.Entity;

namespace WebApp.DAL
{
    public class DataContext : DbContext
    {
        public DataContext(): base("DefaultConnection")
        {

        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>()
                .HasMany(u => u.Roles)
                .WithMany(r=>r.Users)
                .Map(m =>
                {
                    m.ToTable("UserRoles");
                    m.MapLeftKey("UserId");
                    m.MapRightKey("RoleId");
                });

        }
        public DbSet<User> Users { get; set; }
        public DbSet<Role> Roles { get; set; }
    }
}

在我的控制器中,我有一个 DataContext 类型的属性 Context。如何通过角色名称访问该控制器列表中具有角色的所有用户?

【问题讨论】:

    标签: c# .net entity-framework ef-code-first asp.net-mvc-5


    【解决方案1】:

    有一点简单的方法

    var adminUsers = Context.Roles.First(r =&gt; r.Name == "admin").Users

    适用于多种角色

    string[] roles = {"admin","guest"};    
    var users = Context.Roles.Where(r => roles.Any(s => s == r.Name)).SelectMany(r => r.Users)
    

    【讨论】:

    • 我喜欢你的回答。如果有一组字符串与角色名称匹配,你会怎么做?
    • string[] roles = ...; var users = Context.Roles.Where(r =&gt; roles.Any(s =&gt; s == r.Name)).SelectMany(r =&gt; r.Users)
    • 如何在评论中换行? :) 行尾的两个空格不起作用
    【解决方案2】:

    在这种情况下不需要显式连接,只需使用导航属性 Roles 进行查询...

    var adminUsers = Context.Users.Where(u => u.Roles.Any(r => r.Name == "admin"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 2019-02-27
      • 1970-01-01
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多