I use ADO.net Entity Data model for work with database.
In my program, I want to update a record of user table, so I use the code below to do this.
In this function I send changed user info and then overwrite the information with the current user information.
After I run objUser = _user; and then call objContext.SaveChanges(); to save the changes.
But when I do this, the changes are not persisted to the database. I use this code for another programs but in this case the code does not work!
public void Update(tbLiUser _user)
{
LinkContext objContext = this.Context;
tbLiUser objUser = objContext.tbLiUsers.First(u => u.tluId == _user.tluId);
objContext.Attach(objUser);
objUser = _user;
objContext.SaveChanges();
}
First of all, if you already retrieve
objUserfrom theobjContext, there’s really no point in attach that user to the context just after retrieving it. So I would drop this line here entirely:Also – you might just need to update the
objUseron a per-property basis from the values in_userinstead of just assigning the whole object.To help you avoid lots of tedious code, you could use something like AutoMapper to let you assign properties from one object type to the other. Or you could create a smart routine that would compare the two
objUserand_userand update only those properties onobjUserthat are in fact different from the values in_user– shouldn’t be too hard to create that method: