本文介绍了使用 linq 生成无需选择的直接更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好.

我仍在学习 LINQ,所以如果这很幼稚,请原谅我.直接处理 SQL 时,可以生成带条件的更新命令,无需运行 select 语句.

I'm still learning LINQ so forgive me if this is naive. When you're dealing with SQL directly, you can generate update commands with conditionals, without running a select statement.

当我使用 linq 时,我似乎遵循以下模式:

When I work with linq I seem to follow the pattern of:

  1. 选择实体
  2. 修改实体
  3. 提交更改

我想做的是使用 linq 和延迟执行的直接更新.是否有可能直接在 SQL 处执行实际执行而不将任何数据传输到客户端?

What I want to do is a direct update using linq and deferred execution. Is it possible that the actual execution occurs directly at the SQL without any data being transmitted up to the client?

DataContext dc = new DataContext

var q = from product in dc.Products
        where product.Type = 1
        set product.Count = 0

dc.SubmitChanges

所以本质上 LINQ 拥有它需要的所有信息,而无需使用选择来生成更新命令.它将运行 SQL:

So in essence LINQ has all the information it needs WITHOUT using a select to generate an update command. It would run the SQL:

Update Products Set Count = 0 Where Type = 1

LINQ 中是否存在set"这样的关键字?

Does a keyword like "set" exist in LINQ?

推荐答案

不,LINQ 和 LINQ to SQL 都没有基于集合的更新功能.

No, neither LINQ nor LINQ to SQL has set-based update capabilities.

在 LINQ to SQL 中,您必须查询要更新的对象,根据需要更新字段/属性,然后调用 SubmitChanges().例如:

In LINQ to SQL, you must query for the object you wish to update, update the fields/properties as necessary, then call SubmitChanges(). For example:

var qry = from product in dc.Products where Product.Name=='Foobar' select product;
var item = qry.Single();
item.Count = 0;
dc.SubmitChanges();

如果您想进行批处理:

var qry = from product in dc.Products where Product.Type==1 select product;
foreach(var item in qry)
{
  item.Count = 0;
}
dc.SubmitChanges();

或者,您可以自己编写查询:

Alternatively, you could write the query yourself:

dc.ExecuteCommand("update Product set Count=0 where Type=1", null);

这篇关于使用 linq 生成无需选择的直接更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 15:23