问题描述
在 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 中的单个列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!