Spence Spence - 1 year ago 118
SQL Question

Use linq to generate direct update without select

G'day everyone.

I'm still learning LINQ so forgive me if this is naive. When you're dealing with SQL directly, you can generate update commands with conditionals, without running a select statement.

When I work with linq I seem to follow the pattern of:

  1. Select entities

  2. Modify entities

  3. Submit changes

What I want to do is a direct update using linq and deferred execution. Is it possible that the actual execution occurs directly at the SQL without any data being transmitted up to the client?

DataContext dc = new DataContext

var q = from product in dc.Products
where product.Type = 1
set product.Count = 0


So in essence LINQ has all the information it needs WITHOUT using a select to generate an update command. It would run the SQL:

Update Products Set Count = 0 Where Type = 1

Does a keyword like "set" exist in LINQ?

Answer Source

No, neither LINQ nor LINQ to SQL has set-based update capabilities.

In LINQ to SQL, you must query for the object you wish to update, update the fields/properties as necessary, then call SubmitChanges(). For example:

var qry = from product in dc.Products where Product.Name=='Foobar' select product;
var item = qry.Single();
item.Count = 0;

If you wish to do batching:

var qry = from product in dc.Products where Product.Type==1 select product;
foreach(var item in qry)
  item.Count = 0;

Alternatively, you could write the query yourself:

dc.ExecuteCommand("update Product set Count=0 where Type=1", null);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download