将LINQ查询嵌套在另一个查询的where子句中

2vuwiymt  于 2023-06-03  发布在  其他
关注(0)|答案(3)|浏览(541)

如何将以下两个查询组合成一个查询?

using (var ctx = ContextFactory.CreateDbContext())
    {
        int parentId = await ctx.MenuEntity.Where(m => m.Title == thisVariable).Select(m => m.MenuId).SingleAsync();
        menuEntityList = await ctx.MenuEntity.Where(m => m.ParentId == parentId).ToListAsync();
    }
j2qf4p5b

j2qf4p5b1#

此查询等效于sql中的EXISTS

var menuEntityList = context.MenuEntity.Where(
 m => context.MenuEntity.Where(m =>
 m.Title == thisVariable).Any(d => d.MenuId == m.ParentId)
                ).ToList();

我获得了Query with Profiler

exec sp_executesql N'SELECT [m].[Id], [m].[MenuId], [m].[ParentId], [m].[Title]
FROM [MenuEntity] AS [m]
WHERE EXISTS (
    SELECT 1
    FROM [MenuEntity] AS [m0]
    WHERE [m0].[Title] = @__thisVariable_0 
    AND [m0].[MenuId] = [m].[ParentId])'
,N'@__thisVariable_0 nvarchar(4000)',@__thisVariable_0=N'Org'
7kjnsjlb

7kjnsjlb2#

在C#中合并两个LINQ查询

您可以在LINQ中使用Join

代码示例:

using (var ctx = ContextFactory.CreateDbContext())
{
   menuEntityList = await (
        from m in ctx.MenuEntity
        where m.ParentId == ctx.MenuEntity
            .Where(x => x.Title == thisVariable)
            .Select(x => x.MenuId)
            .Single()
        select m
   ).ToListAsync();
}

然而,正如你所看到的,代码并没有提供巨大的优势,我猜这两个选项可能在几乎每一个Angular 都是一样的。

disho6za

disho6za3#

the answer by @AztecCodes的语法略有不同,更像SQL中的IN

using (var ctx = ContextFactory.CreateDbContext())
{
   menuEntityList = await (
        from m in ctx.MenuEntity
        where ctx.MenuEntity
            .Where(x => x.Title == thisVariable)
            .Select(x => x.MenuId)
            .Contains(m.ParentId)
        select m
   ).ToListAsync();
}

相关问题