[英]LINQ to Entities : “select new” expression tree throws System.NotSupportedException
I'm trying to build an Expression Tree that reflects a "select new" query. 我正在尝试构建一个反映“选择新”查询的表达式树。
I'm using Ethan's answer to this question . 我正在使用Ethan对这个问题的答案。 It works great for common lists but with LINQ to Entities I get this exception:
它对于普通列表非常有用,但是对于LINQ to Entities,我得到此异常:
System.NotSupportedException: Unable to create a constant value of type X.
Only primitive types or enumeration types are supported in this context.
Where X is the Entity I'm querying. 其中X是我要查询的实体。
Using the debugger this is the IQueryable with the expression tree: 使用调试器,这是带有表达式树的IQueryable:
SELECT [Extent1].[Id] AS [Id],
[Extent1].[Nombre] AS [Nombre],
[Extent1].[Apellido] AS [Apellido]
FROM [dbo].[Empleadoes] AS [Extent1]
.Select(t => new Nombre;String;() {Nombre = t.Nombre})
And this is the IQueryable using normal linq notation (not actually the same query but to get the point - they are different) 这是使用常规linq表示法的IQueryable(实际上不是相同的查询,但要指出的是-它们是不同的)
SELECT [Extent1].[Dni] AS [Dni],
[Extent1].[Nombre] + N' ' + [Extent1].[Apellido] AS [C1]
FROM [dbo].[Empleadoes] AS [Extent1]
Any help appreciated. 任何帮助表示赞赏。 Thanks.
谢谢。
Looking through Dynamic LINQ code I found the problem. 通过查看动态LINQ代码,我发现了问题。
Ethan's solution does this: Ethan的解决方案做到了:
source.Provider.CreateQuery(
Expression.Call(
typeof(Queryable),
"Select",
new Type[] { source.ElementType, dynamicType },
Expression.Constant(source),
selector));
And inside Dynamic.cs of Dynamic LINQ they do this: 在Dynamic LINQ的Dynamic.cs中,它们执行以下操作:
source.Provider.CreateQuery(
Expression.Call(
typeof(Queryable),
"Select",
new Type[] { source.ElementType, lambda.Body.Type },
source.Expression,
Expression.Quote(lambda)));
The relevant change is in the 4th parameter of the call to Expression.Call. 相关更改在对Expression.Call的调用的第4个参数中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.