EF4 Update Entity Without First Getting Entity

浪尽此生 提交于 2019-12-14 00:15:37

问题


How can I update an entity without having to make a call to select it. If I supply the key for the entity, should it not know to update after SaveChanges() is called on the ObjectContext.

I currently do this:

var user = context.Users.Single(u => u.Id == 2);
user.Username = "user.name";
user.Name = "ABC 123";
context.SaveChanges();

That works, but forces a select. Because I know the Id, why can't I do something like this:

var user = new User();
user.Id = 2;
user.Username = "user.name";
user.Name = "ABC 123";
context.UpdateObject(user);
context.SaveChanges();

Thanks in advance.

EDIT: Also, it's important that only the affected properties that are changed be updated. Is this possible?


回答1:


Maybe following code work fine.

var user = new User();
user.Id = 2;
context.Users.Attach(user);

user.Username = "user.name";
user.Name = "ABC 123";

context.SaveChanges();



回答2:


You can do this in a somewhat artificial way, by adding the entity and changing the EntityState to Modified:

var user = new User();
user.Id = 2;
user.Username = "user.name";
user.Name = "ABC 123";

context.AddToUsers(user);
ObjectStateEntry userEntry = context.ObjectStateManager.GetObjectStateEntry(user);
userEntry.ChangeState(EntityState.Modified);

context.SaveChanges();

In this way you will be telling the ObjectContext to find an entry with Id = 2 and update it rather than adding a new entry to the database.




回答3:


Didn't you have to select it anyway to get it's data to edit? If you cache it it won't cost you anything getting it again when you save it.



来源:https://stackoverflow.com/questions/3204020/ef4-update-entity-without-first-getting-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!