下面的表达式将属性NAME与值PETER进行比较。
ParameterExpression pe = Expression.Parameter(typeof(T), "x");
MemberExpression member = Expression.Property(pe, "name");
ConstantExpression value = Expression.Constant("Peter");
exp = Expression.Equal(member, value);
如果属性是类,该怎么办:
public class Address
{
public string Name {get; set;}
}
然后表达式看起来与此类似:
MemberExpression member = Expression.Property(pe, "Address.Name");
ConstantExpression value = Expression.Constant("Peter");
exp = Expression.Equal(member, value);
这会失败,因为成员类型与值类型不匹配。
所以,问题是:如何使用上面的类样本构建一个表达式?
我在NHibernate.Linq查询中使用此表达式:
var q = from f in data //of type IQueryable<T>
select f;
if (filter != null) //filter of type Expression<Func<T, bool>>
q = q.Where(filter);
etc....
谢谢。
Peter的更新:
基于xanatos的代码(下一篇文章),我创建了以下测试以了解它是如何工作的。它与xanatos没有什么不同,但起初我无法让它工作,所以我决定在一个简单的测试中将它全部写出来,并且这样做了。感谢xanatos:
[Test]
public void FilterWithDeepProperties()
{
//Arrange
IGenericGridRepository repository = ObjectFactory.GetInstance<IGenericGridRepository>();
FilterDescriptor filter = new FilterDescriptor("AgreementId.Name", FilterOperator.IsEqualTo, "a name");
string[] properties = filter.Member.Split('.');
ParameterExpression pe = Expression.Parameter(typeof(SampleDomain), "x");
//Act
Expression lastMember = pe;
for (int i = 0; i < properties.Length; i++)
{
MemberExpression member = Expression.Property(lastMember, properties[i]);
lastMember = member;
}
ConstantExpression valueExpression = Expression.Constant(filter.Value);
Expression equalityExpression = Expression.Equal(lastMember, valueExpression);
Expression<Func<SampleDomain, bool>> where = Expression.Lambda<Func<SampleDomain, bool>>(equalityExpression, pe);
var result = repository.GetObjects<SampleDomain>(filter: where);
//Assert
result.Count().Should().BeGreaterThan(0, "because there are many schedule items equals to " + filter.Value);
}
答案 0 :(得分:1)
您可能需要以下内容:
public static Expression<Func<TSource, bool>> GetEquality<TSource>(object value, params string[] properties)
{
ParameterExpression pe = Expression.Parameter(typeof(TSource), "source");
Expression lastMember = pe;
for (int i = 0; i < properties.Length; i++)
{
MemberExpression member = Expression.Property(lastMember, properties[i]);
lastMember = member;
}
Expression valueExpression = Expression.Constant(value);
Expression equalityExpression = Expression.Equal(lastMember, valueExpression);
Expression<Func<TSource, bool>> lambda = Expression.Lambda<Func<TSource, bool>>(equalityExpression, pe);
return lambda;
}
使用它像:
Expression exp = GetEquality<Person>("Foo", "Address", "Name");
Foo
是Peter
的位置(因此必须比较的值),而Address
和Name
是属性“链”的名称。例如,我正在使用
public class Person
{
public Address Address { get; set; }
}
public class Address
{
public string Name { get; set; }
}
所以生成的表达式是
source.Address.Name == "Foo"
如果您想使用Address.Name
之类的内容,可以使用
Expression exp = GetEquality<Person>("Foo", "Address.Name".Split('.'));