基于这个问题:Why isn't it possible to combine LINQ to XML with LINQ to SQL?我想知道编译器如何确定要使用的 LINQ 提供程序。
问题是使用了 Linq2Xml 和 Linq2Sql,编译器使用了 Linq2Sql。我想知道为什么这是因为使用了两个提供程序:xml 和 sql。
谁能解释一下编译器是如何知道使用哪一个的?
请您参考如下方法:
Linq 方法有不同的重载。其中一些正在运行 IEnumerable<T>其中一些是IQueryable<T> . IEnumerable<T>方法用于 Linq to Objects、Linq to Xml 等。
IQueryable<T>另一方面是为查询提供者创建的。来自 MSDN
The
IQueryable<T>interface is intended for implementation by query providers.This interface inherits the
IEnumerable<T>interface so that if it represents a query, the results of that query can be enumerated. Enumeration forces the expression tree associated with anIQueryable<T>object to be executed. Queries that do not return enumerable results are executed when theExecute<TResult>(Expression)method is called.The definition of "executing an expression tree" is specific to a query provider. For example, it may involve translating the expression tree to a query language appropriate for an underlying data source.
这就是它们的区别所在。但是编译器实际上与此无关,查询的执行完全取决于您运行查询的来源。例如在 Linq to SQL 中,假设您有一个 dbContext.Users。 ,它将返回一个 IQueryable<T>所以你调用这个对象的方法将使用 IQueryable<T>重载,它们可以通过 Linq to SQL 转换为 SQL查询提供者。如果你把它们变成 IEnumerable<T>调用AsEnumerable或其他 linq 方法(ToList、ToArray),结果将从数据库中获取,其余查询将使用 Linq to Objects 在内存中执行。
