gpt4 book ai didi

c# - 创建动态 linq 查询

转载 作者:太空狗 更新时间:2023-10-30 01:11:20 25 4
gpt4 key购买 nike

我有以下查询:

from p in dataContext.Repository<IPerson>()
join spp1 in dataContext.Repository<ISportsPerPerson>() on p.Id equals spp1.PersonId
join s1 in dataContext.Repository<ISports>() on spp1.SportsId equals s1.Id
join spp2 in dataContext.Repository<ISportsPerPerson>() on p.Id equals spp2.PersonId
join s2 in dataContext.Repository<ISports>() on spp2.SportsId equals s2.Id
where s1.Name == "Soccer" && s2.Name == "Tennis"
select new { p.Id };

它选择所有踢足球和网球的人。
在运行时,用户可以选择其他标签添加到查询中,例如:“Hockey”。现在我的问题是,如何将“Hockey”动态添加到查询中?如果将“Hockey”添加到查询中,它将如下所示:

from p in dataContext.Repository<IPerson>()
join spp1 in dataContext.Repository<ISportsPerPerson>() on p.Id equals spp1.PersonId
join s1 in dataContext.Repository<ISports>() on spp1.SportsId equals s1.Id
join spp2 in dataContext.Repository<ISportsPerPerson>() on p.Id equals spp2.PersonId
join s2 in dataContext.Repository<ISports>() on spp2.SportsId equals s2.Id
join spp3 in dataContext.Repository<ISportsPerPerson>() on p.Id equals spp3.PersonId
join s3 in dataContext.Repository<ISports>() on spp3.SportsId equals s3.Id
where s1.Name == "Soccer" && s2.Name == "Tennis" && s3.Name == "Hockey"
select new { p.Id };

如果查询是动态构建的,那就更好了:

private void queryTagBuilder(List<string> tags)
{
IDataContext dataContext = new LinqToSqlContext(new L2S.DataContext());
foreach(string tag in tags)
{
//Build the query?
}
}

有人知道如何正确设置吗?提前致谢!

最佳答案

LINQ 查询在实际执行之前不会被解析。所以你可以这样做:

var q = from r in ctx.records 
/* Do other stuff */
select r;

if (!string.IsNullOrEmpty(search)) {
q = from r in q
where r.title == search
select r;
}

if (orderByName) {
q = q.OrderBy(r => r.name);
}

/* etc */

这将创建一个正在执行的 SQL 语句。

对于您的具体问题:联接使它有些复杂,但我认为您可以加入其他“动态”查询。

所以你最终会得到这样的结果:

var baseQ = from p in dataContext.Repository<IPerson>()
select p;
foreach(var tag in tags) {
baseQ = from p in baseQ
join spp1 in dataContext.Repository<ISportsPerPerson>() on p.Id equals spp1.PersonId
join s1 in dataContext.Repository<ISports>() on spp1.SportsId equals s1.Id
where s1.name == tag
select p;
}

/* If you have defined your relations correct, simplify to something like this.
Does not actually work because of SportsPerPerson probably has multiple sports: */
foreach(var tag in tags) {
baseQ = baseQ.Any(p => p.SportsPerPerson.Sports.Name == tag);
}


var resultQ = from p in baseQ
select new { p.Id };

关于c# - 创建动态 linq 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2817303/

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