【问题标题】:LINQ to Entities : "select new" expression tree throws System.NotSupportedExceptionLINQ to Entities:“选择新”表达式树抛出 System.NotSupportedException
【发布时间】:2023-03-23 19:30:01
【问题描述】:

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

我正在使用 Ethan 对此question 的回答。 它适用于常见列表,但使用 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]

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

【问题讨论】:

    标签: c# linq entity-framework linq-to-entities expression-trees


    【解决方案1】:

    查看Dynamic 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 个参数。

    【讨论】:

      猜你喜欢
      • 2016-04-17
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多