linq - 关于 Entity Framework ,Var vs IEnumerable

标签 linq entity-framework

如果我在下面的代码示例中使用IEnumerable 而不是var,SQL 是否仅在执行foreach 语句时生成?或者它会在评估 Linq 语句时作为 an 执行吗?

var query = db.Customers.Where (c => c.Age > 18);
query = query.Where (c => c.State == "CO");
var result = query.Select (c => c.Name);

foreach (string name in result)   // Only now is the query executed!
   Console.WriteLine (name);

另一个例子:

IEnumerable<Order> query = db.Orders.Where(o => o.Amount > 1000);
int orderCount = query.Count();

使用 var(或 IQueryable)是否会更好,因为它会在执行 .Count() 时执行 select count(*)... 还是与上面显示的 IEnumerable 代码完全相同?

最佳答案

这没什么区别。 var 只是语法糖。如果将鼠标悬停在 var 上,您将看到 C# 认为您的查询是什么类型。

来自 http://msdn.microsoft.com/en-us/library/bb383973.aspx

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

var i = 10; // implicitly typed
int i = 10; //explicitly typed

如果您想对您的查询执行 SQL 不知道该怎么做的操作,例如类中定义的方法,那么您可以使用 AsEnumerable()

例如:

var query = db.Customers
    .Where(c => c.Age > 18)
    .AsEnumerable()
    .Select(c => GetCustomerViewModel());

//put definition of GetCustomerViewModel() somewhere in the same class

更新

如 Omar 所述,如果您希望立即执行查询(而不是延迟执行),请使用 ToList()。这将立即枚举 IQueryable/IEnumerable 并用数据库中的实际数据填充列表。

关于linq - 关于 Entity Framework ,Var vs IEnumerable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7592583/

相关文章:

c# - 如何对包含动态对象的列表进行排序

c# - LINQ 聚合函数到当前行

c# - 从多个表(C#实体)获取数据,通过外键链接,转换为匿名对象

linq - 将 linq 结果转换为 List<MyInterface>

c# - 无法在 EF Core : "42P07: relation "AspNetRoles"already exists"中使用迁移

c# - 具有 if else 条件的 Linq GroupBy 对象

linq - 多对多 EF LINQ

c# - 通过azure管理门户在数据库中添加新表后如何更新现有 Entity Framework

entity-framework - Entity Framework 迁移 API

c# - 如何防止 Entity Framework 强制验证子对象属性?