tags:

views:

79

answers:

1

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.

A: 

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);
Rex M
I thought so, thanks.
Vnuk