How do you do a SQL style 'IN' statement in LINQ to Entities (Entity Framework) if Contains isn't supported?

后端 未结 4 1814
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-13 16:57

I\'m using LINQ to Entities (not LINQ to SQL) and I\'m having trouble creating an \'IN\' style query. Here is my query at the moment:

var items = db.InventoryIt         


        
4条回答
  •  生来不讨喜
    2021-02-13 17:38

    You can use Linq's Any extension method for this in some cases:

    var userIds = new[] { 1, 2, 3 };
    
    from u in Users
         where userIds.Any(i => i==u.Id)
         select u;
    

    The generated SQL looks pretty strange in such a case, but like much Linq-to-Entities generated SQL it might be overly verbose for a human, but runs fast in practice.

    SELECT 
    [Extent1].[Id] AS [Id], 
    [Extent1].[DisplayName] AS [DisplayName], 
    FROM [dbo].[Users] AS [Extent1]
    WHERE  EXISTS (SELECT 
        1 AS [C1]
        FROM  (SELECT 
            [UnionAll1].[C1] AS [C1]
            FROM  (SELECT 
                1 AS [C1]
                FROM  ( SELECT 1 AS X ) AS [SingleRowTable1]
            UNION ALL
                SELECT 
                2 AS [C1]
                FROM  ( SELECT 1 AS X ) AS [SingleRowTable2]) AS [UnionAll1]
        UNION ALL
            SELECT 
            3 AS [C1]
            FROM  ( SELECT 1 AS X ) AS [SingleRowTable3]) AS [UnionAll2]
        WHERE [UnionAll2].[C1] = [Extent1].[Id]
    )
    

提交回复
热议问题