2015-02-24 248 views
0

我想查詢使用Linq to Entities的sql server數據庫。我想用下面的Sql Query對下列表格進行篩選:Linq「Where In」子查詢過濾數據

DECLARE p0... 
SELECT * FROM Boards b 
WHERE b.ownerid = p0 or 
    b.id IN (SELECT s.boardid FROM Shares s WHERE s.userid = p0) 

CREATE TABLE [dbo].[Boards] (
[Id]  INT   IDENTITY (1, 1) NOT NULL, 
[OwnerId] NVARCHAR (128) NULL, 
[ShortName] NVARCHAR (50) NULL, 
...); 

CREATE TABLE [dbo].[Shares] (
    [BoardId] INT   NOT NULL, 
    [UserId] NVARCHAR (128) NOT NULL 
); 

有幾個注意事項,至少會有一個Board行。可以有零到多個共享行。我想返回一個Board行,以及任何具有鏈接共享行的其他Board行。

我已經使用GroupJoin,SelectMany和DefaultIfEmpty執行查詢,以執行等效的TSQL Outer JOIN,但所有這些看起來都比TSql更加複雜。

如何執行Linq中的等效項以篩選結果,以便使用「Where In」SQL語句和OR子句以及父表中的數據?

+0

請參閱:http://stackoverflow.net m/questions/857973/linq-to-entities-sql-in-clause – Habib 2015-02-24 14:05:56

+0

[LINQ中Where where子句]的可能重複(http://stackoverflow.com/questions/959752/where-in-clause-in-linq ) – 2015-03-03 09:04:27

回答

0

你可以這樣做:

var selection = from b in boards 
       where b.ownerid == p0 || 
         (from s in shares 
         where s.userid == p0 
         select s.boardid).Contains(b.id) 
       select b; 

或者,你可以嘗試創建一個名爲其中自動執行此擴展方法:

public static class WhereInExtension 
{ 
    public static IEnumerable<T1> WhereIn<T1, T2>(this IEnumerable<T1> table, IEnumerable<T2> container, Func<T1, T2> converter) 
    { 
     return from b in table 
       where container.Contains(converter(b)) 
       select b; 
    } 
} 

查詢(沒有你的b.ownerid == p0要求)將隨後被調用:

var selection = boards.WhereIn(from s in shares 
           where s.userid == p0 
           select s.boardid, b => b.id);