Issues with ASP.NET 5 MVC 6 and Entity Framework 7

We cannot add Owin and Entity 7 structure together. As we do this, there will be uncertainty between Microsoft.AspNet.Identity.core 2.0.0.0 and Microsoft.AspNet.Identity 3.0.0 Beta1

And therefore, I cannot implement the role provider role in my application to manage user roles.

After this problem, I removed the Owin links and created a UserManager using Microsoft.AspNet.Identity 3.0.0 and EF 7, but UserManager.AddToRoleAsync (user, roleName) always throws an exception, as shown below: -

InvalidOperationException: An instance of the object 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 the IIdentityGenerator generator to generate unique key values.

The code snippet is as follows.

 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");
    }
+4
source share
2 answers

@sanjaypujari

Just try the following:

var user = await context.FindByNameAsync(UserName);
ApplicationUser appuser = (ApplicationUser)user;
var result = await UserManager.AddToRoleAsync(appuser,  RoleName);

When doing this, ApplicationUser should not be tracked twice. The same thing helps if you want to update ApplicationUser.

0
source

. , , , UserManager, :

var user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
var result = await UserManager.AddToRoleAsync(user,  RoleName );

var user = await UserManager.FindByNameAsync(UserName);
var result = await UserManager.AddToRoleAsync(user,  RoleName );
0

All Articles