EntityFrameworkCore 7 SetProperty(avar,avalue) Unable to cast object of type 'System.Linq.Expressions.TypedParameterExpression' to type 'System.Linq.Expressions.LambdaExpression'.

Allen 0 Reputation points
2023-07-25T11:47:25.1166667+00:00

My code:
1.Error

ADal aDal = new ADal();

Func<AModel, float> p = property => property.Balance;

aDal._databaseContext
.ModelDbSet
.Where(w => w.ID == 5)
.Take(1)
.ExecuteUpdate(e => e.SetProperty(p, 636));

Out error (Almost no answer found online):
引发的异常:“System.InvalidCastException”(位于 System.Private.CoreLib.dll 中)

“System.InvalidCastException”类型的未经处理的异常在 System.Private.CoreLib.dll 中发生

Unable to cast object of type 'System.Linq.Expressions.TypedParameterExpression' to type 'System.Linq.Expressions.LambdaExpression'.

2.Normal (Do not use : Func<AModel, float> p = property => property.Balance;)

ADal aDal = new ADal();

aDal._databaseContext
.ModelDbSet
.Where(w => w.ID == 5)
.Take(1)
.ExecuteUpdate(e => e.SetProperty(p => p.Balance, 636));
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
678 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,158 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 52,491 Reputation points
    2023-07-31T17:32:24.8533333+00:00

    with linq to entities (used with db context), the callback are expression trees, not code. the expression tree is a small ast tree of the lambda code. when the query is executed, the driver converts the expression tree to sql syntax. the driver are very restrictive (unlike the compiler) in what code is allowed in the expression.

    https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/expression-trees/

    in you case the driver is telling you it can can not convert the function "p" to sql. how would the SQL Server execute the c# function? how would the driver get the code of the function to generate sql?

    note: some drivers allow you to create sql function and install in the database, and map to a function name.

    0 comments No comments