Как вы можете обработать подзапрос IN с помощью LINQ to SQL?

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

  •  09-06-2019
  •  | 
  •  

Вопрос

Я немного застрял в этом.По сути, я хочу сделать что-то вроде следующего SQL-запроса в LINQ to 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;

Другие советы

Общий способ реализации IN в 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;

Общий способ реализации EXISTS в 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;

Попробуйте использовать два отдельных шага:

// 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

// сначала создаем словарь/набор/коллекцию

Найти другие статьи

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
};

// сначала создаем словарь/набор/коллекцию

Найти другие статьи

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