搜索实体的所有字段
我正在尝试在客户数据库上实现“多function框”搜索,其中单个查询应尝试匹配客户的任何属性。
这里有一些示例数据来说明我想要实现的目标:
FirstName | LastName | PhoneNumber | ZipCode | ... -------------------------------------------------- Mary | Jane | 12345 | 98765 | ... Jane | Fonda | 54321 | 66666 | ... Billy | Kid | 23455 | 12345 | ...
- 如果查询是
"Jane"
,我希望返回第1行以及第2行。 - 对
12345
的查询将产生行#1和#3。
现在,我的代码看起来非常像这样:
IEnumerable searchResult = context.Customer.Where( c => c.FirstName == query || c.LastName == query || c.PhoneNumber == query || c.ZipCode == query // and so forth. Fugly, huh? );
这显然有效。 不过,它对我来说闻起来真的很糟糕,因为实体的任何变化(删除属性,引入新属性)都会破坏东西。
那么:是否有一些LINQ-foo将搜索我投入的任何实体的所有属性?
首先在Customer类中找到与query类型相同的所有属性:
var stringProperties = typeof(Customer).GetProperties().Where(prop => prop.PropertyType == query.GetType());
然后从具有至少一个值等于查询的属性的上下文中查找所有客户:
context.Customer.Where(customer => stringProperties.Any(prop => prop.GetValue(customer, null) == query));