We can't add Owin and Entity framework 7 together. As we do so then there will be ambiguity between Microsoft.AspNet.Identity.core 2.0.0.0 and Microsoft.AspNet.Identity 3.0.0 Beta1
And hence I am not able to implement role provider in my application to manage the user roles.
After facing this issue I removed Owin references and created UserManager using Microsoft.AspNet.Identity 3.0.0 and EF 7 but UserManager.AddToRoleAsync(user, roleName) always throws exception as below:-
InvalidOperationException: The instance of entity type 'Mozaics.DAL.Models.ApplicationUser' cannot be tracked because another instance of this type with the same key is already being tracked. For new entities consider using an IIdentityGenerator to generate unique key values.
Code snippet is like this.
public async Task<ActionResult> RoleAddToUser(string UserName, string RoleName)
{
var user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
var result = await UserManager.AddToRoleAsync(user, RoleName );
ViewBag.ResultMessage = "Role created successfully !";
var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
ViewBag.Roles = list;
return View("ManageUserRoles");
}
I run to this issue. One solution that worked for me was that getting the user via the UserManager and then adding the role:
instead of
var user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
var result = await UserManager.AddToRoleAsync(user, RoleName );
use the following
var user = await UserManager.FindByNameAsync(UserName);
var result = await UserManager.AddToRoleAsync(user, RoleName );