LINQ to SQL: how to update the only field without

2020-03-01 16:08发布

问题:

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!

回答1:

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


回答2:

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.



回答3:

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();