Como você pode lidar com uma subconsulta IN com LINQ to SQL?
-
09-06-2019 - |
Pergunta
Estou um pouco preso nisso.Basicamente, quero fazer algo como a seguinte consulta SQL no LINQ to SQL:
SELECT f.*
FROM Foo f
WHERE f.FooId IN (
SELECT fb.FooId
FROM FooBar fb
WHERE fb.BarId = 1000
)
Qualquer ajuda será muito bem recebida.
Obrigado.
Solução
Dê uma olhada em Este artigo.Basicamente, se você deseja obter o equivalente a IN, primeiro precisa construir uma consulta interna e, em seguida, usar o método Contains().Aqui está minha tentativa de tradução:
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;
Outras dicas
Maneira geral de implementar IN em LINQ to SQL
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;
Maneira geral de implementar EXISTS em LINQ to SQL
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;
Tente usar duas etapas separadas:
// 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
//cria primeiro um dicionário/conjunto/coleção fids
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
Experimente isso
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
};
//cria primeiro um dicionário/conjunto/coleção fids
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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow