问题描述
当我知道实体 ID 时,我想更新实体的唯一字段.
I want to update the only field of entity when I know entity Id.
在 LINQ to SQL 中是否有可能不检索完整实体(来自 DataContext 的所有字段都是开销)?是否可以创建实体并将其附加到 DataContext 并在 DataContext.SubmitChanges(或类似的东西)上标记要同步的确切字段?
Is it possible in LINQ to SQL without retrieving full entity (with all fields from DataContext that is overhead) ? Is it possible to create and attach entity to DataContext and mark the exact field(s) to synchronize on DataContext.SubmitChanges (or something like that)?
先谢谢你!
推荐答案
是的,你可以:
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
这篇关于LINQ to SQL:如何在不检索整个实体的情况下更新唯一字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!