c #Romada中的Dynamic Where子句

时间:2015-12-04 21:41:08

标签: c# entity-framework lambda where

我有一个页面,允许用户按多个字段进行搜索。一个可以使用或全部使用。用户可以将每个字段的运算符设置为等于,包含,开始等等......看起来像这样enter image description here

我正在使用EntityFrame Work并使用像这样的lamba来检索数据:

listOfPeople = adDB.People.Where(x => x.LastName.StartsWith(lastName) && x.FirstName.StartsWith(firstName)).OrderBy(x => x.LastName)

问题是,如何根据用户提供的数据动态创建where子句?

2 个答案:

答案 0 :(得分:3)

你可以使用Func工厂的一些东西来做这件事,因为where子句接受了一个Func。

示例:

public class Program
{
    public static void Main(string[] args)
    {
        var people = new[]
        {   
            new Person {FirstName = "Hello", LastName = "World"}, 
            new Person {FirstName = "Foo", LastName = "Bar"},
        };

        Console.WriteLine(people.Where(FuncFactory.GetFilterFunc<Person>(FilterType.Contains, x => x.FirstName, "ello")).Any());
        Console.WriteLine(people.Where(FuncFactory.GetFilterFunc<Person>(FilterType.Equals, x => x.FirstName, "ello")).Any());
        Console.WriteLine(people.Where(FuncFactory.GetFilterFunc<Person>(FilterType.Contains, x => x.LastName, "ar")).Any());
        Console.WriteLine(people.Where(FuncFactory.GetFilterFunc<Person>(FilterType.Equals, x => x.LastName, "ar")).Any());

        Console.ReadKey();
    }
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public enum FilterType
{
    Contains,
    Equals
}

public static class FuncFactory
{
    public static Func<T, bool> GetFilterFunc<T>(FilterType filterType, Func<T, IComparable> propFunc, string filter)
    {
        switch (filterType)
        {
            case FilterType.Contains:
                return x => (propFunc(x) as string).Contains(filter);
            case FilterType.Equals:
                return x => (propFunc(x) as string).Equals(filter);
            default:
                throw new ArgumentException("Invalid FilterType");
        }
    }
}

答案 1 :(得分:0)

您可能想要使用Predicate Builder:

http://www.albahari.com/nutshell/predicatebuilder.aspx