LINQ to SQL을 사용하여 IN 하위 쿼리를 어떻게 처리할 수 있나요?

StackOverflow https://stackoverflow.com/questions/51339

  •  09-06-2019
  •  | 
  •  

문제

나는 이것에 약간 붙어 있습니다.기본적으로 LINQ to SQL에서 다음 SQL 쿼리와 같은 작업을 수행하고 싶습니다.

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

어떤 도움이라도 감사히 받아들일 것입니다.

감사해요.

도움이 되었습니까?

해결책

보세요 이 기사.기본적으로 IN과 동등한 결과를 얻으려면 먼저 내부 쿼리를 구성한 다음 Contains() 메서드를 사용해야 합니다.내가 번역하려고 시도한 내용은 다음과 같습니다.

var innerQuery = from fb in FoorBar where fb.BarId = 1000 select fb.FooId;
var result = from f in Foo where innerQuery.Contains(f.FooId) select f;

다른 팁

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;
from f in Foo
    where f.FooID ==
        (
            FROM fb in FooBar
            WHERE fb.BarID == 1000
            select fb.FooID

        )
    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

// 먼저 사전/세트/컬렉션 fid를 생성합니다.

다른 기사 찾기

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

이 시도

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
var foos = Foo.Where<br>
( f => FooBar.Where(fb.BarId == 1000).Select(fb => fb.FooId).Contains(f.FooId));
from f in foo
where f.FooID equals model.FooBar.SingleOrDefault(fBar => fBar.barID = 1000).FooID
select new
{
f.Columns
};

// 먼저 사전/세트/컬렉션 fid를 생성합니다.

다른 기사 찾기

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top