简体   繁体   中英

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 . It works great for common lists but with LINQ to Entities I get this exception:

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.

Using the debugger this is the IQueryable with the expression tree:

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)

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.

Ethan's solution does this:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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