实体框架将用户添加到角色 [英] Entity Framework Add User to Role

查看:119
本文介绍了实体框架将用户添加到角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚才提出了一个问题:在这里回答

I asked a question earlier which was answered here

基本上我有2个需要的类:

Basically I have 2 classes that are needed:

public class User : IUser
{
    public string Id { get; set; }

    // Stripped for brevity

    public IList<Role> Roles { get; set; }

    public User()
    {
        this.Id = Guid.NewGuid().ToString();
    }
}

public class Role : IRole
{
    public string Id { get; set; }
    public string Name { get; set; }

    public Role()
    {
        this.Id = Guid.NewGuid().ToString();
    }
}

在我的 DbContext 中有这个声明:

modelBuilder.Entity<User>()
    .HasMany(m => m.Roles)
    .WithMany()
    .Map(m => { 
        m.MapLeftKey("UserId");
        m.MapRightKey("RoleId"); 
        m.ToTable("UserRoles"); 
    });

这一切都很完美。现在,我想添加一个用户到一个特定的角色,所以我创建了一个服务,遵循我的服务/仓库/工作单位的设计模式,如下所示:

That all works perfectly. Now, I want to add a user to a specific role, so I created a service following my service / repository / unit of work design pattern like this:

public class UserRoleService : Service<UserRole>
{
    public UserRoleService(IUnitOfWork unitOfWork)
        : base(unitOfWork)
    {

    }

    public async Task<IList<UserRole>> GetAllAsync(string userId, params string[] includes)
    {
        return await this.Repository.GetAll(includes).Where(m => m.UserId.Equals(userId, StringComparison.OrdinalIgnoreCase)).ToListAsync();
    }

    public async Task CreateAsync(UserRole model)
    {
        var isInRole = await IsInRole(model.UserId, model.RoleId);

        if (isInRole)
            throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.UserInRole, new object[] { model.RoleId }));

        this.Repository.Create(model);
    }

    public async Task RemoveAsync(UserRole model)
    {
        var isInRole = await IsInRole(model.UserId, model.RoleId);

        if (!isInRole)
            throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.UserNotInRole, new object[] { model.RoleId }));

        this.Repository.Remove(model);
    }

    public async Task<bool> IsInRole(string userId, string roleId)
    {
        if (string.IsNullOrEmpty(userId))
            throw new ArgumentNullException("userId");

        if (string.IsNullOrEmpty(userId))
            throw new ArgumentNullException("roleId");

        var roles = await this.GetAllAsync(userId);
        var match = roles.Where(m => m.RoleId.Equals(roleId, StringComparison.OrdinalIgnoreCase)).SingleOrDefault();

        return (match == null);
    }
}

继承的服务类如下所示:

The inherited service class looks like this:

public class Service<T> where T : class
{
    private readonly IRepository<T> repository;

    protected IRepository<T> Repository
    {
        get { return this.repository; }
    }

    public Service(IUnitOfWork unitOfWork)
    {
        if (unitOfWork == null)
            throw new ArgumentNullException("unitOfWork");

        this.repository = unitOfWork.GetRepository<T>();
    }
}

现在,因为我的 DbContext 没有 DbSet ,因为 UserRoles 它抱怨,所以我添加了一个。然后我有一个抱怨说,新表没有设置主键,所以我添加了一个。所以现在我的 DbContext 看起来像这样:

Now, because my DbContext doesn't have a DbSet for UserRoles it complains, so I added one. Then I got a complaint that the new table does not have a primary key set up, so I added one. So now my DbContext looks like this:

public class DatabaseContext : DbContext
{
    // Removed for brevity
    public DbSet<Role> Roles { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<UserRole> UserRoles { get; set; }

    static DatabaseContext()
    {
        //Database.SetInitializer<IdentityContext>(null); // Exsting database, do nothing (Comment out to create database)
    }

    public DatabaseContext()
        : base("DefaultConnection")
    {
        base.Configuration.LazyLoadingEnabled = false; // Disable Lazy Loading
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); // Remove Cascading Delete

        // Removed from brevity
        modelBuilder.Entity<UserRole>().HasKey(m => new { m.UserId, m.RoleId });
        modelBuilder.Entity<User>()
            .HasMany(m => m.Roles)
            .WithMany()
            .Map(m => { 
                m.MapLeftKey("UserId");
                m.MapRightKey("RoleId"); 
                m.ToTable("UserRoles"); 
            });
    }
}

我现在遇到的问题是我的代码创建 UserRole 的两个表格称为 UserRoles UserRoles1
有人可以告诉我如何让它只使用一个表?

The problem I have now, is that my code creates two tables for UserRole called UserRoles and UserRoles1. Can someone tell me how to get it to only use one table?

推荐答案

如果UserRole代表一个纯映射(即它只包含UserId和RoleId,没有其他属性),实际上并不需要一个UserRole对象。在您的DbContext(您已经完成)中定义关系就足够了。为了将特定角色与特定用户相关联,您可以简单地执行以下操作:

If UserRole represents a pure mapping (i.e. it contains only UserId and RoleId, and no other properties), you do not actually need a UserRole object. It is enough to define the relationship in your DbContext (which you have done). In order to associate a particular role with a particular user, you can simply do:

user.Roles.Add(role);

...并提交DbSet

...and commit the DbSet

实体框架足够聪明,可以为您维护多对多映射表,而无需实际表示映射本身的实体。

Entity Framework is smart enough to maintain the many-to-many mapping table for you without actually having an entity that represents the mapping itself.

这篇关于实体框架将用户添加到角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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