I am new to MVC 5 asp.net Identity model and was looking for means to customise standard Asp.net Identity to suit my needs. Through blog on TypeCast Exception and one at Stackoverflow: How to model Identity I was able to create my own elements in ApplicationUser and ApplicationRole tables. However, my requirement is to add new columns to UserRole table, DATE_FROM and DATE_TO which I did by implementing IdentityUserRole
interface. My problem is when I'm trying to save the link UserManager.AddRoleToUser takes only two parameters, UserName and RoleName. How to store parameters for custom 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;
}
the SelectUserRolesViewModel supplies extended IdnetityUserRole model. Any pointer will be appreciated.
If you add additional properties to the ApplicationUserRole table, you can't use AddUserToRole
method anymore. Because AddUserToRole
method is from UserManagerExtensions
class which is sealed class, you cann't create your own class to inherit from UserManagerExtensions
. I'm not sure there are any better solution for this, but below is a working example.
Add additional properties to the ApplicationUserRole
table:
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; }
}
Then you can create a new ApplicationUserRole
instance like below:
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With