0

I am trying to update entity but the entity framework do not save changes

this is my code

public bool updateUser(user CUser)
{
            CurrentUser = (CustomPrincipal)HttpContext.Current.User;
            user userToBeUpdated = context.users.Where(user => user.user_id == CurrentUser.Id).FirstOrDefault();

            userToBeUpdated  = CUser;

            context.SaveChanges();
            return true;
}

does there anything wrong in my code?

Update

public bool updateUser(user CUser)
{
    CurrentUser = (CustomPrincipal)HttpContext.Current.User;
    user userToBeUpdated = context.users.Where(user => user.user_id == CurrentUser.Id).FirstOrDefault();
    CUser.user_id = userToBeUpdated.user_id;
    CUser.date_created = userToBeUpdated.date_created;

    if (CUser.Password == "hidden")
        CUser.Password = userToBeUpdated.Password;
    else
        CUser.Password = new Hash().GetBcryptHashedPassword(CUser.Password);

    if (CUser.UDTO.File.ContentLength > 0)
    {
        FileHelper ProfilePicture = new FileHelper(CUser.UDTO.File, "jpg,jpeg,png", 5, true, 500, 500);
        if (!checkUserPersonalImage(CUser.UDTO.File, CUser, ProfilePicture, CurrentUser))
        {
            return false;
        }
        CUser.PersonalImage = ProfilePicture.uploadFile();
    }
    else
    {
        CUser.PersonalImage = userToBeUpdated.PersonalImage;
    }   

    if (!checkRoleValidity(CUser, CurrentUser, false, false))
    {
        return false;
    }
    if (!checkDepartmentValidity(CUser, CurrentUser, false, false))
    {
        return false;
    }
    userToBeUpdated = CUser;
    context.Entry(userToBeUpdated).State = System.Data.Entity.EntityState.Modified;
    context.SaveChanges();
    new UserHelperMethods().updateUserHolderLists(CurrentUser.Company, CUser);
    CUser.UDTO.RedirectTo = "AddNewUser";
    CUser.UDTO.Message="<div class='success'>User has been updated successfully</div>";
    CUser.UDTO.Company = CurrentUser.Company;
    return true;
}

this is the complete function and I got the following error

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

Mo Haidar
  • 3,748
  • 6
  • 37
  • 76
  • welp. your function does not return anything. you probaby skipped something important. Is any exception thrown? – DevilSuichiro Sep 19 '15 at 17:50
  • I just noticed.... your function does virtually nothing besides fetch data from the database... – DevilSuichiro Sep 19 '15 at 17:57
  • @DevilSuichiro no exceptions – Mo Haidar Sep 19 '15 at 18:30
  • 1
    `userToBeUpdated = CUser;` doesn't do what you think it does. – Claies Sep 19 '15 at 18:32
  • @Claies I used to update a field in the entity by changing its value and then call the` context.SaveChanges()` for example `userToBeUpdated.X = 15; context.SaveChanges();` and then it saves the changes so I think that `userToBeUpdated = CUser `changes works the same like `userToBeUpdated .X = 15;` – Mo Haidar Sep 19 '15 at 18:34
  • so what is the correct way to update the entity – Mo Haidar Sep 19 '15 at 18:37
  • you have to ensure the ID value is the same of those. Set the entity state of the new entry to modified. this will tell EF to create an UPDATE statement upon calling SaveChanges(). – DevilSuichiro Sep 19 '15 at 19:08
  • @DevilSuichiro could you check the update above, I updated my code and I get that error. – Mo Haidar Sep 19 '15 at 19:46
  • oh, right. you have to modify your retrieved value, or detach the old one and then attach the new – DevilSuichiro Sep 19 '15 at 19:47
  • You might have a look at my answer on [ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value](http://stackoverflow.com/questions/23201907/asp-net-mvc-attaching-an-entity-of-type-modelname-failed-because-another-ent/39557606#39557606). – Murat Yıldız Sep 18 '16 at 12:32

1 Answers1

3

I used to update a field in the entity by changing its value and then call thecontext.SaveChanges() for example userToBeUpdated.X = 15; context.SaveChanges(); and then it saves the changes so I think that userToBeUpdated = CUser changes works the same like userToBeUpdated .X = 15

You are quite wrong in assuming that userToBeUpdated.X=15 and userTobeUpdated=CUser does the same thing. The original object that the userToBeUpdated variable referenced is still tracked by EF. After that you change the reference of the userToBeUpdated variable to an instance of another object and attach it to the DbContext. The dbcontext now tries to track two objects: the user it retrieved from the database and a second object that has the same primary key. EF balks at that and throws an exception.

So the .X=15 approach is the correct one. You should update all relevant properties on the userToBeUpated from CUser and then save changes.

Dabblernl
  • 15,831
  • 18
  • 96
  • 148