views:

47

answers:

2

I need to load an object from the database, modify some of its fields and relations, and then I want to store a new value for only one field, without modifying the rest.

It would look something like this:

var thing = db.Things.First();

thing.Field1 = "asdas";
thing.Field2 = 23;
thing.OtherThings.Add(new OtherThing());
thing.FieldToUpdate = doSomething(thing);

db.SaveChanges();

But that would save all the changes, what I want is to only save FieldToUpdate...

I've looked around and all I've found is to use stored procedures, which seems like too much for something that looks so simple, besides I would have to make a different stored procedure for each time I need to do something like this...

My current solution is to open another context, load the thing again, update the FieldToUpdate and SaveChanges, but that's both inefficient and ugly.

A: 

The Entity Framework is smart enough to figure out what has changed and what hasn't and optimizes the SQL statement is uses accordingly. If you only change FieldToUpdate, then the SQL statement will only be an update on the single field, not on everything.

However, if you do change Field1 and Field2 from what they were originally, they will be persisted too, but ONLY if they changed. Otherwise, there's no need to tell the DB to change it to what it already is.

Entity framework does it this way because that's exactly what the developer wants 99.9% of the time. If you are going to use an entity object as an object that you want to move around and manipulate in ways other than treating it as a model of the database (like it should be), then you may want to consider creating another new wrapper class that lets you mess with all the data fields that you want (and have others that aren't in there), and then have the save method of it do the proper entity framework persistance, to keep things separate and clean.

Ryan Hayes
+1  A: 

If you want to do this with attached entity you have to update FieldToUpdate FIRST and call SaveChanges. Than you can update other fields and call SaveChanges again if needed. No other way with attached entity.

Other way you can try is to detach entity, modify what you want to (it will not track changes). Then attach entity back to context and call:

// I suppose that db is ObjectContext or inherited type
db.ObjectStateManager.GetObjectStateEntry(thing).SetModifiedProperty("FieldToUpdate");

Now only FieldToUpdate is tracked as changed.

Ladislav Mrnka