繁体   English   中英

LINQ to Entities:“选择新”表达式树将引发System.NotSupportedException

[英]LINQ to Entities : “select new” expression tree throws System.NotSupportedException

我正在尝试构建一个反映“选择新”查询的表达式树。

我正在使用Ethan对这个问题的答案。 它对于普通列表非常有用,但是对于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.

其中X是我要查询的实体。

使用调试器,这是带有表达式树的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})

这是使用常规linq表示法的IQueryable(实际上不是相同的查询,但要指出的是-它们是不同的)

SELECT [Extent1].[Dni] AS [Dni],
       [Extent1].[Nombre] + N' ' + [Extent1].[Apellido] AS [C1]
FROM [dbo].[Empleadoes] AS [Extent1]

任何帮助表示赞赏。 谢谢。

通过查看动态LINQ代码,我发现了问题。

Ethan的解决方案做到了:

source.Provider.CreateQuery(
    Expression.Call(
        typeof(Queryable),
        "Select",
        new Type[] { source.ElementType, dynamicType },
        Expression.Constant(source),
        selector));

在Dynamic LINQ的Dynamic.cs中,它们执行以下操作:

source.Provider.CreateQuery(
    Expression.Call(
        typeof(Queryable),
        "Select",
        new Type[] { source.ElementType, lambda.Body.Type },
        source.Expression,
        Expression.Quote(lambda)));

相关更改在对Expression.Call的调用的第4个参数中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM