Reputation: 12283
I am trying to compare if a property of an object has the value of int. How to achieve it, please?
int id = 123;
// Func<MyClass, bool> f = x => x.A.B.Id == id;
var a = System.Linq.Expressions.MemberExpression.Property(param, "A");
var b = System.Linq.Expressions.MemberExpression.Property(a, "B");
body = System.Linq.Expressions.Expression.Equal(
System.Linq.Expressions.MemberExpression.Property(b, "Id"),
System.Linq.Expressions.MemberExpression.Constant(id, typeof(int))
);
This throws invalidoperation exception.
Upvotes: 0
Views: 1162
Reputation: 1501163
It's not clear what you're doing wrong, because you haven't shown enough of your code or enough of the error. The general approach is fine. Here's a short but complete example:
using System;
using System.Linq.Expressions;
public class House
{
public Person Owner { get; set; }
}
public class Person
{
public string Name { get; set; }
}
class Test
{
static void Main()
{
int targetLength = 3;
var param = Expression.Parameter(typeof(House), "p");
var a = Expression.Property(param, "Owner");
var b = Expression.Property(a, "Name");
var length = Expression.Property(b, "Length");
var target = Expression.Constant(targetLength, typeof(int));
var body = Expression.Equal(length, target);
var lambda = Expression.Lambda<Func<House, bool>>(body, param);
var compiled = lambda.Compile();
var house = new House { Owner = new Person { Name = "Jon" } };
Console.WriteLine(compiled(house));
house.Owner.Name = "Holly";
Console.WriteLine(compiled(house));
}
}
I suggest you look at the difference between my code and your code to work out what's wrong.
Upvotes: 1
Reputation: 12283
I found it out. The propert ID was not Int32, it was Int16. My fault. For the others. Check the object property type 3-times before you leave :)
Upvotes: 0