我的数据库中有一个表Products
。我有一个像
var ids = new[] { 10, 12, 1000, 1100 };
在我的表中,产品10和20确实存在,而1000,1100不存在。如何编写优化的linq查询以获取表中不存在的项? (1000,1100)
我认为优化查询就像
select
a.y
from
(select 10 as y
union all
select 12 as y
union all
select 800 as y
union all
select 8000 as y) as a
where
a.y not in (select p.Id from Products as p);
如何使用linq生成这样的查询?
答案 0 :(得分:2)
这应该有效:
var ids = new[] { 10, 12, 1000, 1100 };
var result = ids.Except(dbContext.Products.Where(p => ids.Contains(p.ID)).Select(p => p.ID)).ToList();
答案 1 :(得分:0)
答案
var ids = new[] { 10, 12, 1000, 1100 };
var result = (from p in dbContext.Products
where ids.Contains(p.ID)
select p).ToList();