I'm in a dbFirst situation and I've got the standard AspNetUser tables on my sql server. I've implemented IUserStore, IUserPasswordStore and IUserSecurityStampStore successfully on my UserStore class. I am now trying to implement IUserRoleStore.
All I want to do is associate users with a role.
My current (rather naiive) implmentation of AddToRoleAsync is thus:
public Task AddToRoleAsync(PortalUser user, string role) { var context = _userStore.Context as BackOfficeEntities; user.AspNetRoles.Add(context.AspNetRoles.First(r => r.Name.Equals(role,StringComparison.InvariantCulture))); return context.SaveChangesAsync(); }
the thing is, when I call UserManager in my controller in the following way:
var currentUser = await UserManager.FindByNameAsync(model.UserName); if (currentUser != null) {
var roleAddResult = await UserManager.AddToRoleAsync(currentUser.Id, role);
}
UserManager calls my UserStore AddToRoleAsync method fine but then goes on to call my UserStore UpdateAsync method. The UpdateAsync call chokes with "An object with the same key already exists in the ObjectStateManager"
Here's the UpdateAsync method (the ToUser() is an extention method to coerce the PortalUser object to a User type):
public Task UpdateAsync(PortalUser user) { var context = _userStore.Context as BackOfficeEntities; context.Users.Attach(user.ToUser()); context.Entry(user.ToUser()).State = EntityState.Modified; context.Configuration.ValidateOnSaveEnabled = false; return context.SaveChangesAsync(); }
Given there's precious little documentation and no source and I can't read the ASP.Net team's mind, I have no idea why the UpdateAsync is being called. The record in the ASPNetUserRoles table is being persisted fine but obviously the process is being borked by the call to UpdateAsync.
I'm a bit of an EF novice so maybe my lack of knowledge is the problem here. Anyway thanks to anybody who can let me know. Alternatively the ASP.Net Identity team could release the source or provide some adequate documentation.
TIA