Use linq to generate direct update without select

前端 未结 7 865
感情败类
感情败类 2020-11-29 05:34

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

相关标签:
7条回答
  • 2020-11-29 06:34

    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
    
    0 讨论(0)
提交回复
热议问题