在 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 中的单个列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
LINQ to SQL:如何在不检索整个实体的情况下更新唯LINQ to SQL: how to update the only field without retrieving whole entity(LINQ to SQL:如何在不检索整个实体的情况下更新唯一字段)
string1 >= string2 未在 Linq to SQL 中实现,有什string1 gt;= string2 not implemented in Linq to SQL, any workaround?(string1 gt;= string2 未在 Linq to SQL 中实现,有什么解决方法吗?)
如何在条件下使用 RemoveAll 删除列表中的多个项目How to Remove multiple items in List using RemoveAll on condition?(如何在条件下使用 RemoveAll 删除列表中的多个项目?)
转换表达式树Convert Expression trees(转换表达式树)
当 IDENTITY_INSERT 设置为 OFF 时,无法为表“ClientCannot insert explicit value for identity column in table #39;ClientDetails#39; when IDENTITY_INSERT is set to OFF(当 IDENTITY_INSERT 设置为 OFF 时,
Linq 独特的 &最大限度Linq distinct amp; max(Linq 独特的 amp;最大限度)