سؤال

I am developing an asp.net mvc5 ef5 app. I use ef code first approach. I have two tables User(UserId,Name) and Role(RoleId, Name). My DataContext class look like that:

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

In my controller I have a property Context of type DataContext. How can I access in that controller list of all users with a role by the role name?

هل كانت مفيدة؟

المحلول

There is a little bit simple way

var adminUsers = Context.Roles.First(r => r.Name == "admin").Users

For many roles

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

نصائح أخرى

There's no explicit join necessary in this case, simply query using the navigation property Roles...

var adminUsers = Context.Users.Where(u => u.Roles.Any(r => r.Name == "admin"));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top