搜索实体的所有字段

vzw*_*ick 14 c# linq linq-to-entities properties entity-framework-4

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

这里有一些示例数据来说明我想要实现的目标:

FirstName  | LastName  | PhoneNumber | ZipCode | ...
--------------------------------------------------
Mary       | Jane      | 12345       | 98765   | ...
Jane       | Fonda     | 54321       | 66666   | ...
Billy      | Kid       | 23455       | 12345   | ...
Run Code Online (Sandbox Code Playgroud)
  • 如果查询是"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?
);
Run Code Online (Sandbox Code Playgroud)

这显然有效.然而,它对我来说闻起来真的很糟糕,因为实体的任何变化(删除属性,引入新属性)都会破坏东西.

那么:是否有一些LINQ-foo将搜索我投入的任何实体的所有属性?

Biz*_*han 15

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

var stringProperties = typeof(Customer).GetProperties().Where(prop =>
    prop.PropertyType == query.GetType());
Run Code Online (Sandbox Code Playgroud)

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

context.Customer.Where(customer => 
    stringProperties.Any(prop =>
        prop.GetValue(customer, null) == query));
Run Code Online (Sandbox Code Playgroud)

  • 精彩的解决方案!仅供参考,`query`实际上是一个字符串,因为我正在处理`WebApi`.因此,我最终迭代所有属性(不仅是字符串)并在它们上调用`.ToString()`(显然在进程中捕获`null`值).`.Any`部分现在看起来像这样:`.Any(prop =>((prop.GetValue(customer,null)== null)?"":prop.GetValue(customer,null).ToString().ToLower ())==查询)` (3认同)