将LINQ表达式作为参数传递

时间:2017-01-27 00:56:54

标签: c# entity-framework linq

我有一个Entity Framework类设置为从SQL数据库中读取表,但我无法弄清楚如何传递LINQ表达式来仅过滤某些对象。我知道有一种方法可以构建一个表达式树,并在类中动态地执行此操作,但我似乎无法找到最佳方法。

任何提示都表示赞赏。

class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class MyObjectCollection<T> where T : class
{
    private List<T> myInternalCollection = new List<T>();

    MyObjectCollection()
    {
        using (var db = new MyContext()) 
        {
            foreach (T row in db.Set<T>())
            {
                // Enumerate the data, do whatever with it...
                myInternalCollection.Add(row);
            }
        }
    }

    MyObjectCollection(var MyLinqExpression)
    {
        using (var db = new MyContext()) 
        {
            foreach (T row in db.Set<T>().Where.MyLinqExpression()
            {
                // Enumerate the data, do whatever with it...
                myInternalCollection.Add(row);
            }
        }
    }
}

// Works fine:
MyObjectCollection<Customer> allCustomers = new MyObjectCollection<Customer>();

// Would like something like this:
MyObjectCollection<Customer> customersP = new MyObjectCollection<Customer>(c => c.StartsWith("P"));

1 个答案:

答案 0 :(得分:2)

Linq Where方法采用Func<T, bool>参数,其中T将是您要应用Where方法的dbSet对象类型。

为了使您的代码有效,您可以这样做:

public MyObjectCollection(Func<T, bool> MyLinqExpression)
{
    using (var db = new MyContext())
    {
        foreach (T row in db.Set<T>().Where(MyLinqExpression))
        {
            // Enumerate the data, do whatever with it...
            myInternalCollection.Add(row);
        }
    }
}

更新: 此外,要使用泛型集合实现您正在寻找的功能,而不是封装私有List对象,您可以从List继承,如下所示。因此,如果您希望MyObjectCollection像List一样运行,您可以执行类似我在下面显示的操作。

因此,使用上面的代码,您可以更改为:

public class MyObjectCollection<T> : List<T> where T : class
{
    public MyObjectCollection()
    {
        using (var db = new MyContext())
        {
            foreach (T row in db.Set<T>())
            {
                // Enumerate the data, do whatever with it...
                this.Add(row);
            }
        }
    }

    public MyObjectCollection(Func<T, bool> MyLinqExpression)
    {
        using (var db = new MyContext())
        {
            foreach (T row in db.Set<T>().Where(MyLinqExpression))
            {
                // Enumerate the data, do whatever with it...
                this.Add(row);
            }
        }
    }
}
相关问题