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