Reputation: 2703
Is it possible to do a partial update through linq2sql?
If I want to update only 2 fields I would use sql like
update table set col1 = val1, col2 = val2 where id = @id
I find the "fetch it from database, change it and then update" process a bit, well ineffective, if not just weird.
Upvotes: 0
Views: 819
Reputation: 60093
Yes, you can generate update statements without doing a fetch:
Foo foo=new Foo { FooId=fooId }; // create obj and set keys
context.Foos.Attach(foo);
foo.Name="test";
context.SubmitChanges();
see https://stackoverflow.com/a/3351534/52817
Upvotes: 1
Reputation: 144182
LINQ (Language Integrated Query) is for querying, not full CRUD. LINQ-to-SQL handles the Update, Delete, and Create actions via a typical object model.
Since you already have the ID of the object you want to update, we will assume you have that entity object in LINQ (e.g. from item in table where id=1 select item
):
myItem.Col1 = "val1";
myItem.Col2 = "val2";
dataContext.SubmitChanges();
This works for one-off updates where you have a specific record to change.
If, for some reason, you do not have the original entity object but have the ID, you can execute arbitrary SQL via the DataContext:
dataContext.ExecuteQuery(
"UPDATE table SET col1={0}, col2={1} WHERE ID={3}",
value1,
value2,
id);
Upvotes: 0