如何在不加载整行的情况下更新 LINQ 中的单个列?

How to update a single column in LINQ without loading the entire row?(如何在不加载整行的情况下更新 LINQ 中的单个列?)
本文介绍了如何在不加载整行的情况下更新 LINQ 中的单个列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 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.

这篇关于如何在不加载整行的情况下更新 LINQ 中的单个列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)
How to store delegates in a List(如何将代表存储在列表中)
How delegates work (in the background)?(代表如何工作(在后台)?)
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)