4
我正在构建一个基于SearchObject的相当大的过滤器,该搜索对象有50多个可以搜索的字段。为什么谓词在通过反射进行构建时没有被过滤
而不是建立我的每个单独的where子句,我认为我会使用一些轻微的手,并尝试构建提供必要信息的自定义属性,然后使用反射来构建每个谓词语句(使用LinqKit BTW)。麻烦的是,代码在反射代码中找到了适当的值,并成功地为该属性构建了一个谓词,但“where”似乎并未实际生成,并且我的查询始终返回0条记录。
属性很简单:
[AttributeUsage(AttributeTargets.Property, AllowMultiple=true)]
public class FilterAttribute: Attribute
{
public FilterType FilterType { get; set; } //enum{ Object, Database}
public string FilterPath { get; set; }
//var predicate = PredicateBuilder.False<Metadata>();
}
这是我的方法建立了查询:
public List<ETracker.Objects.Item> Search(Search SearchObject, int Page, int PageSize)
{
var predicate = PredicateBuilder.False<ETracker.Objects.Item>();
Type t = typeof(Search);
IEnumerable<PropertyInfo> pi = t.GetProperties();
string title = string.Empty;
foreach (var property in pi)
{
if (Attribute.IsDefined(property, typeof(FilterAttribute)))
{
var attrs = property.GetCustomAttributes(typeof(FilterAttribute),true);
var value = property.GetValue(SearchObject, null);
if (property.Name == "Title")
title = (string)value;
predicate.Or(a => GetPropertyVal(a, ((FilterAttribute)attrs[0]).FilterPath) == value);
}
}
var res = dataContext.GetAllItems().Take(1000)
.Where(a => SearchObject.Subcategories.Select(b => b.ID).ToArray().Contains(a.SubCategory.ID))
.Where(predicate);
return res.ToList();
}
的SearchObject很简单:
public class Search
{
public List<Item> Items { get; set; }
[Filter(FilterType = FilterType.Object, FilterPath = "Title")]
public string Title { get; set; }
...
}
任何建议将不胜感激。我很可能会走错方向,如果有人有更好的替代方案(或至少有一个方法可行),就不会冒犯。
只是一个念头。是否谓词。或者将等式测试中的值作为常量或参考来处理?如果作为参考,那么Where在寻找特定的参考,但没有找到它们。 – Handcraftsman 2010-10-26 05:04:32