How do we create an AS expression in Expression tree builder? https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-cast#as-operator
We have an Iqueryable, we want to check a property of the object.
By doing so we use Expression.Convert
to convert the parameterexpression to a class.
Afterwards we get an error we try to run this query on the DbContext:
'Unable to cast the type 'System.Object' to type 'System.Data.Entity.DynamicProxies.Ourclass'. LINQ to Entities only supports casting EDM primitive or enumeration types.'
Code we use:
Expression<Func<object, bool>> Example<T>(T customeType)
{
ParameterExpression e = Expression.Parameter(typeof(object));
var converted = Expression.Convert(e, customeType.GetType());
MemberExpression u = Expression.MakeMemberAccess(converted, "IsDeleted");
BinaryExpression isDeleted = Expression.Equal(u, Expression.Constant(false));
Expression<Func<object, bool>> lambda = Expression.Lambda<Func<object, bool>>(isDeleted, e);
return lambda;
}
The above code compiles to something like: m => ((OurClass)m).IsDeleted == false
.
However this is not valid code for Linq to Entities.
We want something like m => (m as OurClass).IsDeleted == false
.
Is it possible to generate a dynamic expression?
We do not want to use ToList for performance reasons.