搜索某个实体的各个领域 [英] Search on all fields of an entity

查看:71
本文介绍了搜索某个实体的各个领域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现在一个客户数据库在一个单一的查询应该尝试匹配客户的任何属性的多功能框式的搜索。

I'm trying to implement an "omnibox"-type search over a customer database where a single query should attempt to match any properties of a customer.

下面是一些样本数据来说明我想要实现的:

Here's some sample data to illustrate what I'm trying to achieve:

FirstName  | LastName  | PhoneNumber | ZipCode | ...
--------------------------------------------------
Mary       | Jane      | 12345       | 98765   | ...
Jane       | Fonda     | 54321       | 66666   | ...
Billy      | Kid       | 23455       | 12345   | ...




  • 如果查询是,我期望排#1要返回以及排#2。

  • 系统查询 12345 会产生行#1和#3

    • If the query was "Jane", I'd expect row #1 to be returned as well as row #2.
    • A query for 12345 would yield rows #1 and #3.
    • 现在,我的代码看起来非常像这样:

      Right now, my code looks pretty much like this:

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

      这显然有效。它闻起来像真的不好的做法对我来说,虽然,因为在实体(去除特性,引入新的属性)将打破东西的任何变化

      This obviously works. It smells like really bad practice to me, though, since any change in the Entity (removal of properties, introduction of new properties) would break stuff.

      所以:有一些LINQ-foo的,将跨越任何实体我扔在所有属性搜索?

      So: is there some LINQ-foo that will search across all properties of whatever Entity I throw at it?

      推荐答案

      先找到客户类中的所有属性与同类型的查询:

      first find all properties within Customer class with same type as query:

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



      然后找到所有的客户从至少有一个财产价值等于查询上下文:

      then find all customers from context that has at least one property with value equal to query:

      context.Customer.Where(customer => 
          stringProperties.Any(prop =>
              prop.GetValue(customer, null) == query));
      

      这篇关于搜索某个实体的各个领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆