gpt4 book ai didi

c# - Entity Framework : Update inside LINQ query

转载 作者:太空狗 更新时间:2023-10-29 23:22:01 24 4
gpt4 key购买 nike

我遇到了这样一种想法:在 LINQ 查询中更新表,而不是先进行查询,然后更新该查询返回的每个对象。

例如,可以更改此查询中与 x 关联的任何属性的值:

var Query = from x in EFContext.SomeTable
where x.id == 1
// SET X = Model or x.Name = "NewName"
select SaveChanges();

这样的事情能做吗?

最佳答案

来自 MSDN :

In a query that returns a sequence of values, the query variable itself never holds the query results and only stores the query commands. Execution of the query is deferred until the query variable is iterated over in a foreach or for loop. This is known as deferred execution; that is, query execution occurs some time after the query is constructed. This means that you can execute a query as frequently as you want to. This is useful when, for example, you have a database that is being updated by other applications. In your application, you can create a query to retrieve the latest information and repeatedly execute the query, returning the updated information every time.

因此,当您执行 foreach 更新您的实体时,您的查询将被执行。正如@recursive 所说,当您需要对集合进行查询而不是专门更新数据时,LINQ 很有用。

作为附加信息,您还可以强制立即执行。这在您想要缓存查询结果时非常有用,例如,当您想要使用 Linq to Entities 不支持的某些功能时。要强制立即执行不产生单一值的查询,您可以调用 ToList 方法、ToDictionary 方法或 ToArray查询或查询变量上的方法。

关于c# - Entity Framework : Update inside LINQ query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28509567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com