I've been looking for a solution to this for a few days now and only found answers related to older versions of Identity Framework.
Project uses c# Asp.net MVC 6 Entity Framework 7 beta8 and Identity Framework 3.0.0-beta Code-First Data. In a simple project I'm trying to implement an Admin only User information/editor page which will allow to edit all user properies by accessing UserStore or UserManager and save the changes to the standard Identity Framework user store in DBcontext.
Here's the ApplicationUser Model code with the extra fields:
public class ApplicationUser : IdentityUser { [Display(Name = "Last Name")] [DataType(DataType.Text)] [StringLength(50)] public string UserLastName { get; set; } [Display(Name = "First Name")] [DataType(DataType.Text)] [StringLength(50)] public string UserFirstName { get; set; } [Display(Name = "User")] public override string UserName { get; set; } } The corresponding Controller code for the Index view:
public class UserListController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; public UserListController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager) { _userManager = userManager; _signInManager = signInManager; } // GET: Index public IActionResult Index() { var userStore = new UserStore<ApplicationUser>(new ApplicationDbContext()); var listofUsers = userStore.Users.ToList(); if (listofUsers == null) { return new HttpStatusCodeResult(404); } return View(listofUsers); } Index View has an Edit action which passes the selected User's Id:
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) And the rest of the Controller code:
// GET: Edit [HttpGet] public IActionResult Edit(Guid? id) { if (id == null) { return new HttpStatusCodeResult(404); } var userStore = new UserStore<ApplicationUser>(new ApplicationDbContext()); ApplicationUser userforEdit = userStore.Users.SingleOrDefault(x => x.Id == id.ToString()); if (userforEdit == null) { return new HttpStatusCodeResult(404); } return View(userforEdit); } // POST: Edit [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(ApplicationUser editedUser) { if (ModelState.IsValid) { var UpdateUserResult = await _userManager.UpdateAsync(editedUser); return RedirectToAction("Index"); } return View(editedUser); } } }
Error exception during execution of
var UpdateUserResult = await _userManager.UpdateAsync(editedUser); InvalidOperationException: The instance of entity type 'UserManagement.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.
I partially understand the twice instantiated problem but cannot find the proper method or at least a workaround. Every DB migrations have been updated and applied to the DB with dnvm ef migrations. Thanks for any help!