Search code examples
c#asp.netasp.net-mvcentity-frameworkasp.net-identity

EntityState.Modified Error "entity of the same type already has the same primary key value"


I got following error while running Edit [Post] method:

Attaching an entity of type 'MyType.Models.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.

I create a new instance of ApplicationUser class (Identity framework) with all required fields and save it to database for an existing user, as a response to user "Edit" [Post] action, 'db' is a private variabile of type MyDbContext. I simplified code for readability.

Here is my controller:

public ActionResult Edit([Bind(Include = "Id,a,b,c,d,e")] ModelClass editParam)
    {
            ApplicationUser user = new ApplicationUser()
            {
                Id = editParam.Id,
                a= editParam.a,
                b = editParam.b,
                c= editParam.c,
                d= editParam.d,
                e= editParam.e,
            };

            string[] userRoles = editParam.Roles.Split(new[] { ", " }, StringSplitOptions.None); 
            var userStore = new UserStore<ApplicationUser>(db);
            var userManager = new UserManager<ApplicationUser>(userStore);


            userManager.RemoveFromRoles(user.Id, GetAllUserRoles()); 
            userManager.AddToRoles(user.Id, userRoles);
            db.Entry(user).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("UsersList");
    }

This is my model class:

public class ModelClass
    {
            public string Id { get; set; }

            [Required]
            public string a { get; set;}

            [Required]          
            public string b { get; set; }

            [Required]
            public string c { get; set; }

            [Required]
            public string d { get; set; }

            [Required]
            public string e { get; set; }

            [Required]
            public string f { get; set; }

            [Required]
            public string g { get; set; }

            [Required]
            public string h { get; set; }   

            public int i { get; set; }
    }

Solution

  • Can you please tell me what happens, when you try this?:

    //I named my dbcontext, yours has a different class name
    //My class name, as an example, is called NoId, yours is different
    using (BreazEntities29 entity = new BreazEntities29())
    {
        var id = entity.NoIds.Where(r => r.Id == 1).ToList();
    
        //if you are calling into a method, where you can not have control of AsNoTracking(),
        //then you can put the foreach statement shown here after calls into db change methods
    
        //credit to https://stackoverflow.com/questions/27423059/how-do-i-clear-tracked-entities-in-entity-framework
        //foreach (var db in entity.ChangeTracker.Entries())
        //{
        //    db.State = EntityState.Detached;
        //}
    
        NoId noid = new NoId { Id = 1, NoId1 = "new" };
        entity.Entry(noid).State = EntityState.Modified;
    }
    
    return RedirectToAction("UsersList");