如何在不加载整行的情况下更新 LINQ 中的单个列?
- 作者: Alwayshere32782496
- 来源: 51数据库
- 2022-12-15
问题描述
在 LinqToSql 中,加载行、更改列并将更改提交到数据库非常简单:
In LinqToSql, it is lovely easy to load a row, change a column, and submit the changes to the database:
using (MyDataContext wdc = new MyDataContext())
{
Article article = wdc.Article.First(p => p.ID == id);
article.ItemsInStock = itemsinstock;
wdc.SubmitChanges();
}
唯一的缺点:文章很大.要加载整篇文章,仅更新一列是一种矫枉过正的方式,并且会显着降低我的应用速度.
The only drawback: Article is huge. To load the entire article, just to update one column is way overkill and slows down my app significantly.
有没有办法使用 LINQ 更新单列,而不必加载整行?
Is there a way to update a single column using LINQ, without having to load the entire row?
现在我在速度至关重要的地方恢复使用 ExecuteCommand,但这很丑陋且容易出错:
Right now I revert to using ExecuteCommand where speed is of essence, but this is ugly and error prone:
wdc.ExecuteCommand("UPDATE Article SET ItemsInStock = @1 WHERE ID = @2", itemsinstock,id);
推荐答案
ligget78 给了我另一个关于如何更新单列的想法:
ligget78 gave me another idea how to make an update of a single column:
为这种更新创建一个新的 DataContext,并且只将需要的列包含到这个 DataContext 中.
Create a new DataContext just for this kind of update, and only include the needed columns into this DataContext.
这样不需要的列就不会被加载,当然也不会送回数据库.
This way the unneeded columns will not even be loaded, and of course not sent back to the database.
- 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 包还原找不到包,没有源
