为什么这个LINQ连接查询工作,但另一个不起作用?

时间:2021-02-14 14:32:21

I've written two LINQ queries using the join method. Essentially, if I switch the order of the objects to be joined, the query no longer works and throws the error:

我使用join方法编写了两个LINQ查询。基本上,如果我切换要连接的对象的顺序,查询将不再起作用并抛出错误:

"Unable to create a constant value of type 'Domain.Entities.UsersSitesRole'. Only primitive types ('such as Int32, String, and Guid') are supported in this context."

“无法创建类型为'Domain.Entities.UsersSitesRole'的常量值。在此上下文中仅支持基本类型(例如Int32,String和Guid')。”

        var foo2 = //works
            from p in privilegesForUser
            join c in repository.Child on p.SiteId equals c.Child_SiteID
            select new { ChildID = c.Child_ChildID, name = c.Child_FirstName, site = c.Child_SiteID, p.PrivilegeLevel };

        var foo3 = //throws exception
            from c in repository.Child
            join p in privilegesForUser on c.Child_SiteID equals p.SiteId
            select new { ChildID = c.Child_ChildID, name = c.Child_FirstName, site = c.Child_SiteID, p.PrivilegeLevel };

The object privilegesForUser is a List of entities derived from my Entity Framework context (UsersSiteRole), and repository.Child is an IQueryable<Child> from my EF context as well.

对象privilegesForUser是从我的Entity Framework上下文(UsersSiteRole)派生的实体列表,repository.Child也是来自我的EF上下文的IQueryable

1 个解决方案

#1


4  

This is caused by the way EF parses the expression tree it gets in the extension methods.

这是由EF解析它在扩展方法中获得的表达式树的方式引起的。

There are many cases, where a query is logically correct and executes just fine on IEnumerable (Linq to Objects) but fails in Linq to Entities. Basicly, it's pretty much impossible to compile just any logical expression tree into proper SQL statements (SQL is not ideal and far from object oriented world) and this is the case where EF gives up. In time, you get used to understanding what works and what doesn't.

在许多情况下,查询在逻辑上是正确的,并且在IEnumerable(Linq to Objects)上执行得很好但在Linq to Entities中失败。基本上,几乎不可能将任何逻辑表达式树编译成适当的SQL语句(SQL不理想,远离面向对象的世界),这就是EF放弃的情况。随着时间的推移,你会习惯了解哪些有效,哪些无效。

#1


4  

This is caused by the way EF parses the expression tree it gets in the extension methods.

这是由EF解析它在扩展方法中获得的表达式树的方式引起的。

There are many cases, where a query is logically correct and executes just fine on IEnumerable (Linq to Objects) but fails in Linq to Entities. Basicly, it's pretty much impossible to compile just any logical expression tree into proper SQL statements (SQL is not ideal and far from object oriented world) and this is the case where EF gives up. In time, you get used to understanding what works and what doesn't.

在许多情况下,查询在逻辑上是正确的,并且在IEnumerable(Linq to Objects)上执行得很好但在Linq to Entities中失败。基本上,几乎不可能将任何逻辑表达式树编译成适当的SQL语句(SQL不理想,远离面向对象的世界),这就是EF放弃的情况。随着时间的推移,你会习惯了解哪些有效,哪些无效。