开发者

Update doesn't work in ADO.net Entity Data model

开发者 https://www.devze.com 2023-01-07 03:35 出处:网络
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.

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 开发者_如何学CobjUser = _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 objUser from the objContext, there's really no point in attach that user to the context just after retrieving it. So I would drop this line here entirely:

objContext.Attach(objUser);

Also - you might just need to update the objUser on a per-property basis from the values in _user instead 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 objUser and _user and update only those properties on objUser that are in fact different from the values in _user - shouldn't be too hard to create that method:

objUser.UpdateValuesFromOtherUser(_user);
objContext.SaveChanges();
0

精彩评论

暂无评论...
验证码 换一张
取 消