MVC 5:Asp.net身份:如何建模UserRole

sid*_*mar 5 asp.net-mvc asp.net-mvc-5 asp.net-identity

我是MVC 5 asp.net身份模型的新手,正在寻找自定义标准Asp.net身份的方法以满足我的需求.通过对博客的类型转换异常,一个在#1:如何识别模块,我能够创造ApplicationUser和ApplicationRole表我自己的元素.但是,我的要求是将新列添加到UserRole表,DATE_FROM和DATE_TO,这是我通过实现IdentityUserRole接口所做的.我的问题是当我试图保存链接UserManager.AddRoleToUser只接受两个参数,UserName和RoleName.如何存储自定义参数ApplicationUserRole

public bool AddUserToRole(string userId, SelectUserRolesViewModel roleName)
{
                var um = new UserManager<ApplicationUser>(
                    new UserStore<ApplicationUser>(new ApplicationDbContext()));


                var idResult = um.AddToRole(userId, roleName);
                return idResult.Succeeded;
            }
Run Code Online (Sandbox Code Playgroud)

SelectUserRolesViewModel提供扩展的IdnetityUserRole模型.任何指针将不胜感激.

Lin*_*Lin 3

如果您向 ApplicationUserRole 表添加其他属性,则无法AddUserToRole再使用方法。因为AddUserToRole方法来自UserManagerExtensions密封类的类,所以您无法创建自己的类来继承UserManagerExtensions。我不确定是否有更好的解决方案,但下面是一个可行的示例。

向表中添加附加属性 ApplicationUserRole

public class ApplicationUserRole : IdentityUserRole
{
    public DateTime DateFrom { get; set; }
    public DateTime DateTo { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }
    public DbSet<ApplicationUserRole> ApplicationUserRoles { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后您可以创建一个新ApplicationUserRole实例,如下所示:

    using (var _db = new ApplicationDbContext())
    {
        var roleName = //Get role name from somewhere here
        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_db));
        if (!roleManager.RoleExists(roleName))
        {
             var newRoleresult = roleManager.Create(new IdentityRole()
             {
                  Name = roleName,
             });
        }
        var userRole = new ApplicationUserRole
        {
            UserId = currentUser.Id,
            RoleId = roleManager.FindByName(roleName).Id,
            DateFrom = DateTime.Now,
            DateTo = DateTime.Now.AddDays(1)
        };
        _db.ApplicationUserRoles.Add(userRole);
        _db.SaveChanges();
   }
Run Code Online (Sandbox Code Playgroud)