T
Thirumalai Muniswmy
Guest
I am writing an expression tree in C# for evaluating equal match and finding whether one of the property on an entity matching with some predefined constant and taking action as per the result. As I am not sure what kind of object will be an input for the expression, I used ExpandoObject and coded expression tree as per that.
When I run the code, I could not get the result as per the condition. Always it resulting false.
var dynEmp = System.Text.Json.JsonSerializer.Deserialize<ExpandoObject>("{\"Id\":1,\"Name\":\"Test Name\"}");
ParameterExpression dynpe = Expression.Parameter(typeof(object), "employee");
DynamicExpression dynme = Expression.Dynamic(CreateGetMemberBinder(typeof(object), "Id"), typeof(object), dynpe);
ConstantExpression dynconstant = Expression.Constant(1, typeof(object));
BinaryExpression dynbody = Expression.Equal(dynme, dynconstant);
var dynexpressionTree = Expression.Lambda<Func<dynamic, bool>>(dynbody, new[] { dynpe });
var dynfunc = dynexpressionTree.Compile();
var result = dynfunc(dynEmp);
Console.WriteLine(result);
The CreateGetMemberBinder method -
private static GetMemberBinder CreateGetMemberBinder(Type type, string memberName)
{
return (GetMemberBinder)Microsoft.CSharp.RuntimeBinder.Binder.GetMember(
Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags.None,
memberName,
type,
new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }
);
}
Please correct me the issue on this code.
Many Thanks, Thirumalai M
Continue reading...
When I run the code, I could not get the result as per the condition. Always it resulting false.
var dynEmp = System.Text.Json.JsonSerializer.Deserialize<ExpandoObject>("{\"Id\":1,\"Name\":\"Test Name\"}");
ParameterExpression dynpe = Expression.Parameter(typeof(object), "employee");
DynamicExpression dynme = Expression.Dynamic(CreateGetMemberBinder(typeof(object), "Id"), typeof(object), dynpe);
ConstantExpression dynconstant = Expression.Constant(1, typeof(object));
BinaryExpression dynbody = Expression.Equal(dynme, dynconstant);
var dynexpressionTree = Expression.Lambda<Func<dynamic, bool>>(dynbody, new[] { dynpe });
var dynfunc = dynexpressionTree.Compile();
var result = dynfunc(dynEmp);
Console.WriteLine(result);
The CreateGetMemberBinder method -
private static GetMemberBinder CreateGetMemberBinder(Type type, string memberName)
{
return (GetMemberBinder)Microsoft.CSharp.RuntimeBinder.Binder.GetMember(
Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags.None,
memberName,
type,
new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }
);
}
Please correct me the issue on this code.
Many Thanks, Thirumalai M
Continue reading...