【问题标题】:How to build a query like the selectbyexample using linq-to-entities?如何使用 linq-to-entities 构建类似于 selectbyexample 的查询?
【发布时间】:2011-12-02 11:03:44
【问题描述】:

如何使用 linq-to-entities 构建类似于 selectbyexample 的查询?

例如:

public class Person
{
      public string Name {get; set;}
      public int Age {get; set;}
      public string City {get; set;}
}

如果我有一个 new Person(),其中所有属性的值为 null,则查询应该返回 Person 表的所有记录。

但是如果我传递一个属性为 Age = 25 的对象,查询应该返回我所有年龄 = 25 的记录;

我想构建一个查询过滤器来接受任何属性,如果要忽略它为 null。

【问题讨论】:

  • 您可以每分钟 GC.Collect() 一个这样的对象,直到您的要求得到满足。 xkcd.com/982

标签: c# linq entity-framework linq-to-entities


【解决方案1】:
       var p = new Person {Age = 25};

       src.Where(el => p.Age == null ? true : el.Age == p.Age)
           .Where(el => p.Name == null ? true : el.Name == p.Name)
           .Where(el => p.City == null ? true : el.City == p.City);

在您的 Person 类中,Age 应该可以为空(int?而不是 int)。

【讨论】:

    【解决方案2】:

    首先,您的示例不能将所有属性都设为 null,因为 Age 不可为空。

    无论如何都是这样完成的:

    public static IQueryable<Person> QueryByExample(Person example, YourContext context)
    {
        var query = context.Persons;
    
        if (example.Name != null) 
        {
           string name = example.Name;
           query = query.Where(p => p.Name == name);
        }
    
        // Same for other properties
    
        return query;
    }
    

    【讨论】:

      【解决方案3】:

      您需要一个自定义的 Linq 方法。这是你可以做到的:

      http://msdn.microsoft.com/en-us/library/cc981895.aspx

      这可以帮助您了解如何动态迭代您的类属性

      c# - How to iterate through classes fields and set properties

      【讨论】:

        猜你喜欢
        • 2013-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多