17

我正在尝试在客户数据库上实现“多功能框”类型的搜索,其中单个查询应尝试匹配客户的任何属性。

以下是一些示例数据来说明我想要实现的目标:

FirstName  | LastName  | PhoneNumber | ZipCode | ...
--------------------------------------------------
Mary       | Jane      | 12345       | 98765   | ...
Jane       | Fonda     | 54321       | 66666   | ...
Billy      | Kid       | 23455       | 12345   | ...
  • 如果查询是"Jane",我希望返回第 1 行以及第 2 行。
  • 查询12345将产生行#1 和#3。

现在,我的代码看起来很像这样:

IEnumerable<Customer> searchResult = context.Customer.Where(
    c => c.FirstName   == query ||
         c.LastName    == query ||
         c.PhoneNumber == query ||
         c.ZipCode     == query
         // and so forth. Fugly, huh?
);

这显然有效。不过,这对我来说闻起来像是非常糟糕的做法,因为实体中的任何更改(删除属性,引入新属性)都会破坏东西。

那么:是否有一些 LINQ-foo 可以搜索我扔给它的任何实体的所有属性?

4

1 回答 1

18

首先在 Customer 类中找到与查询相同类型的所有属性:

var stringProperties = typeof(Customer).GetProperties().Where(prop =>
    prop.PropertyType == query.GetType());

然后从上下文中找到至少一个属性值等于查询的所有客户:

context.Customer.Where(customer => 
    stringProperties.Any(prop =>
        prop.GetValue(customer, null) == query));
于 2012-10-11T17:38:02.913 回答