且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

LINQ to SQL:如何在不检索整个实体的情况下更新唯一字段

更新时间:2023-09-10 18:27:52

是的,你可以:

Foo foo=new Foo { FooId=fooId }; // create obj and set keys
context.Foos.Attach(foo);
foo.Name="test";
context.SubmitChanges();

在您的 Dbml 中,为所有属性设置 UpdateCheck="Never".

In your Dbml set UpdateCheck="Never" for all properties.

这将生成一个没有选择的更新语句.

This will generate a single update statement without a select.

一个警告:如果您希望能够将 Name 设置为 null,则必须将 foo 对象初始化为不同的值,以便 Linq 可以检测到更改:

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