使用Linq表达式作为具有父/子查询的规范模式

时间:2010-07-01 15:15:49

标签: c# linq domain-driven-design linq-expressions

我正在尝试使用实现为Linq表达式的规范模式,以便Linq提供程序可以解析它以生成有效的数据库查询。

This给出了基本的想法。

我很难尝试让它使用父/子查询

class Parent
{
    public int Foo;

    public IList<Child> Children = new List<Child>();
}

class Child
{
    public int Bar;
}

class Program
{
    static void Main(string[] args)
    {
        IQueryable<Parent> qry = GetQry(); //initialised


        //This works but duplicates the IsBigBar() logic
        //Included to show what I am trying to query on
        var parentsWithBigChildBars =
                from parents in qry
                where parents.Children.Any(child => child.Bar > 10) 
                select parents;

        var parentsWithBigChildBars2 =
               from parents in qry
               where parents.Children.Any( ?? ) //but how do i access my IsBigBar() expression from here?
               select parents;
    }


    //I want to re-use it to pull parents back!
    public Expression<Func<Child, bool>> IsBigBar()
    {
        return child => child.Bar > 10;
    }

    //I'f i use this as the Any() delegate, it compiles & runs but not an expression so evaluated client side
    public Func<Child, bool> IsBigBar2()
    {
        return child => child.Bar > 10;
    }
}

1 个答案:

答案 0 :(得分:1)

你想:

    var predicate = IsBigBar();
    var parentsWithBigChildBars2 =
           from parents in qry
           where parents.Children.Any(predicate) 
           select parents;

额外var 非常重要。它阻止查询提供程序(拥有qry)尝试解释IsBigBar(),而是将其指向该方法的结果