Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

c# - 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

dc.SubmitChanges

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can actually let LINQ-to-SQL generate update statements:

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 having to do a select first.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...