gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:08:25 25 4
gpt4 key购买 nike

我正在尝试使用作为 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;
}
}

最佳答案

你想要:

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

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

关于c# - 使用 Linq 表达式作为具有父/子查询的规范模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3159148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com