views:

143

answers:

3

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?

A: 

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.

Jeroen
In a typical web app you do the select, generate a page containing the Id's, and "forget about it". After the user updates the info and submits the form, you get back the Id and the new data. This is when you want to JUST update, rather than fetch the data you don't need one extra time before updating.
Yakimych
@Yakimych - Yeah that's exactly the situation that I'm working with. I don't really need to do a trip to the db to select it even though I have the data.
TheCloudlessSky
+2  A: 

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.

Yakimych
Ok that's cool. The works but *one* problem. What if I only want to change the `Name` property. I don't want all the fields to cause an update. Is this a limitation with EF?
TheCloudlessSky
+3  A: 

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();
That doesn't actually *update* the object in the database. It adds it to the list of users though.
TheCloudlessSky
Calling `context.ObjectStateManager.GetObjectStateEntry(user).ChangeState(EntityState.Modified);` does perform the update...
TheCloudlessSky
Do you change the Name property after "context.Users.Attach(user);"?
Yup, my mistake. This works great modifying the properties *after* the `Attach()` and when a property is modified, it only updates the *changed* property. Thanks!
TheCloudlessSky
It should be noted though that if you did a `foreach` on `context.Users` that you would see the `User` *not* filled with the other properties.
TheCloudlessSky