LINQ to SQL:如何在不检索整个实体的情况下更新唯一字段
- 作者: 夕阳下奔跑的姨妈
- 来源: 51数据库
- 2022-12-15
问题描述
当我知道实体 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
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
