Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL: how to update the only field without retrieving whole entity

I want to update the only field of entity when I know entity Id.

Is it possible in LINQ to SQL without retrieving full entity (with all fields from DataContext that is overhead) ? Is it possible to create and attach entity to DataContext and mark the exact field(s) to synchronize on DataContext.SubmitChanges (or something like that)?

Thank you in advance!

like image 839
Andrew Florko Avatar asked Jul 21 '10 16:07

Andrew Florko


3 Answers

Yes you can:

Foo foo=new Foo { FooId=fooId }; // create obj and set keys
context.Foos.Attach(foo);
foo.Name="test";
context.SubmitChanges();

In your Dbml set UpdateCheck="Never" for all properties.

This will generate a single update statement without a select.

One caveat: if you want to be able to set Name to null you would have to initialize your foo object to a different value so Linq can detect the change:

Foo foo=new Foo { FooId=fooId, Name="###" };
...
foo.Name=null;

If you want to check for a timestamp while updating you can do this as well:

Foo foo=new Foo { FooId=fooId, Modified=... }; 
// Modified needs to be set to UpdateCheck="Always" in the dbml
like image 94
laktak Avatar answered Nov 15 '22 05:11

laktak


You can always create a standard T-SQL statement and execute that against your data store:

YourDataContext
  .ExecuteCommand("UPDATE dbo.YourTable SET ThatField = newValue WHERE ID = 777", null);

With Linq-to-SQL itself, you cannot do this - it's basic assumption is that it always operates on the object, the whole object, and nothing but the object.

If you need to do this on a regular basis, one way would be to wrap it into a stored proc and add that stored proc to your data context as a method you can call on the data context.

like image 1
marc_s Avatar answered Nov 15 '22 06:11

marc_s


You can refresh the object. This example will change the person's first name:

Person person = _entities.Persons.FirstOrDefault(p => p.Id == id);
person.FirstName = "Bill";
_entities.Refresh(System.Data.Objects.RefreshMode.ClientWins, person);
_entities.SaveChanges();
like image 1
gnome Avatar answered Nov 15 '22 05:11

gnome