0

I have this code to update the email address using Identity framework's UserManager:

UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ApplicationDbContext.Create()));
ApplicationUser user = await UserManager.FindByNameAsync(username);
IdentityResult result = null;
if (user != null)
{
    user.Email="foo";
    result = await UserManager.UpdateAsync(user);
}

however whenever I try to run it, it throws this error:

System.InvalidOperationException: Attaching an entity of type 'ApplicationUser' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

For the most part I'm just using out-of-the-box identity framework as it appears in the default MVC template in Visual Studio. No custom user stores or anything. I'm not sure what I'm doing wrong here.

Matthew
  • 4,149
  • 2
  • 26
  • 53
  • 1
    Perhaps you already have a user by the name foo? – MX D Jun 01 '18 at 14:20
  • @MXD I'm testing it in a database with only one user. Also I set the configuration option to allow duplicate email addresses (it identifies users by UserName, which is different from Email) – Matthew Jun 01 '18 at 14:24
  • @Matthew, perhaps the top answer [here](https://stackoverflow.com/questions/20444022/updating-user-data-asp-net-identity) helps? – SubjectiveKirby Jun 01 '18 at 14:33
  • What is that .Create() method on the ApplicationDbContext? Can't say I've seen that before and cannot find it referenced on the IdentityDbContext... – Steve Py Jun 02 '18 at 00:22

1 Answers1

0

Try changing the state of your entity to Modified like this:

var context = ApplicationDbContext.Create();
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
ApplicationUser user = await UserManager.FindByNameAsync(username);
IdentityResult result = null;
if (user != null)
{
    context.Entry(user).State = System.Data.EntityState.Modified;
    user.Email="foo";
    result = await UserManager.UpdateAsync(user);
}
othman.Da
  • 621
  • 4
  • 16