如何使用单个查询来检查两个表中是否存在值

时间:2019-06-20 15:14:48

标签: c# entity-framework-core

使用EF Core 2.2.2,我有以下两个简单查询,目的是确定ColorCollectionItem表中是否使用PuzzleColor

var isACollectionItem = _applicationDbContext.CollectionItem.Any(collectionItem => collectionItem.ColorId == color.Id);
var isAPuzzleItem = _applicationDbContext.PuzzleColor.Any(puzzleColor => puzzleColor.ColorId == color.Id);
var eitherOr = 
        _applicationDbContext.CollectionItem.Any(collectionItem => collectionItem.ColorId == color.Id)
    ||  _applicationDbContext.PuzzleColor.Any(puzzleColor => puzzleColor.ColorId == color.Id);

前两行生成两个单独的查询,如下所示:

SELECT CASE
    WHEN EXISTS (
        SELECT 1
        FROM [CollectionItem] AS [collectionItem]
        WHERE [collectionItem].[ColorId] = @__color_Id_0)
    THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT)
END

使用||运算符将它们放在一起意味着在第一个查询不正确的情况下将同时运行它们,否则将仅运行第一个查询。

是否可以使用EF将两个检查合并到一个查询中?

1 个答案:

答案 0 :(得分:1)

我可以通过使用Color表(我没写在我的原始帖子中,很糟糕)作为一个查询:

bool singleQuery = _applicationDbContext.Color
    .Any(myColor =>
            myColor.Id == _applicationDbContext.CollectionItem.FirstOrDefault(collectionItem => collectionItem.ColorId == color.Id).ColorId
        ||  myColor.Id == _applicationDbContext.PuzzleColor.FirstOrDefault(puzzleColor => puzzleColor.ColorId == color.Id).ColorId);

其中翻译成:

SELECT CASE
    WHEN EXISTS (
        SELECT 1
        FROM [Color] AS [myColor]
        WHERE ([myColor].[Id] = (
            SELECT TOP(1) [collectionItem].[ColorId]
            FROM [CollectionItem] AS [collectionItem]
            WHERE [collectionItem].[ColorId] = @__color_Id_0
        )) OR ([myColor].[Id] = (
            SELECT TOP(1) [puzzleColor].[ColorId]
            FROM [ServedColor] AS [puzzleColor]
            WHERE ([puzzleColor].[Discriminator] = N'PuzzleColor') AND ([puzzleColor].[ColorId] = @__color_Id_1)
        )))
    THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT)
END

我想可以通过使用联接或联合来创建性能更高的查询