c# - Entity Framework : Update inside LINQ query

标签 c# linq entity-framework

我遇到了这样一种想法:在 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/

相关文章:

c# - 您的自定义类与数据库有何关系

c# - 这是使用异常的正确方法吗?

c# - LINQ 表达式提取数字的特定数量和值

c# - 多个 child 的 Entity Framework linq 查询

c# - 发布 ASP.NET 与复制文件

c# - Lambda 表达式 if-else 语句在 where 子句中

asp.net - Controller 中的 Linq 查询时间太长

javascript - 使用按钮加载 View 单击新页面 MVC

c# - Entity Framework : How to query a model from other methods before DbContext is disposed?

c# - 删除 dataGridView 中的选定行