如何使用LINQ to SQL處理IN子查詢?



3 Answers

在LINQ to SQL中實現IN的一般方法

var q = from t1 in table1
        let t2s = from t2 in table2
                  where <Conditions for table2>
                  select t2.KeyField
        where t2s.Contains(t1.KeyField)
        select t1;

在LINQ to SQL中實現EXISTS的一般方法

var q = from t1 in table1
        let t2s = from t2 in table2
                  where <Conditions for table2>
                  select t2.KeyField
        where t2s.Any(t1.KeyField)
        select t1;
Question

我對此有點困惑。 基本上我想在LINQ to SQL中執行類似以下SQL查詢的操作:

SELECT f.* 
FROM Foo f
WHERE f.FooId IN (
    SELECT fb.FooId
    FROM FooBar fb
    WHERE fb.BarId = 1000
)

我們將非常感激地提供任何幫助。

謝謝。




嘗試這個

var fooids = from fb in foobar where fb.BarId=1000 select fb.fooID
var ff = from f in foo where f.FooID = fooids select f



嘗試使用兩個單獨的步驟:

// create a Dictionary / Set / Collection fids first
var fids = (from fb in FooBar
            where fb.BarID = 1000
            select new { fooID = fb.FooID, barID = fb.BarID })
            .ToDictionary(x => x.fooID, x => x.barID);

from f in Foo
where fids.HasKey(f.FooId)
select f



from f in foo
where f.FooID equals model.FooBar.SingleOrDefault(fBar => fBar.barID = 1000).FooID
select new
{
f.Columns
};



Related