使用LINQ生成没有选择直接更新直接、LINQ

2023-09-02 01:35:17 作者:染指红颜笑′

每个人儿真好

我还在学习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:

选择实体 修改实体 提交修改

我想要做的是使用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?

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);