我看过其他几篇问类似问题的帖子,但坦率地说,我很困惑。我正尝试在EntityFarmework和Linq中执行以下sql语句,但无法执行'NOT IN‘和'UNION’语句
SELECT LmsTeam.* FROM LmsTeam
INNER JOIN Game ON LmsTeam.GameId = Game.ID
WHERE LmsTeam.Id NOT IN
(SELECT TeamHomeId as TeamID FROM LmsEventMatch WHERE EventId =1
UNION
SELECT TeamAwayId as TeamID FROM LmsEventMatch WHERE EventId =1)
AND LmsTeam.GameId = 1 AND LmsTeam.Active = 1所以我得到了下面的join和一些where子句,但不能处理NOT IN和UNION子句。
from t in LmsTeams
join g in Games on t.GameId equals g.Id
where t.GameId == 1 && t.Active == true
select t发布于 2013-03-27 18:59:56
这个怎么样:
from t in LmsTeams
join g in Games on t.GameId equals g.Id
where t.GameId == 1 && t.Active == true && !(
(from m in LmsEventMatch where m.EventId == 1 select m.TeamHomeId).Union(
from m in LmsEventMatch where m.EventId == 1 select m.TeamAwayId)
).Contains(t.Id)
select t我没有测试它,因为没有您的数据上下文,但我认为应该这样做。
更新
我认为你可以在这里避免使用Union:
from t in LmsTeams
join g in Games on t.GameId equals g.Id
where t.GameId == 1 && t.Active == true && !(
LmsEventMatch.Where(m => m.EventId == 1).SelectMany(m => new int[] { m.TeamHomeId, TeamAwayId })
).Contains(t.Id)
select t发布于 2014-03-05 02:46:02
另一种解决方案是使用Left outer join,并保留连接列为null的记录。
下面给出一个示例:
var query = db.Categories
.GroupJoin(db.Products,
Category => Category.CategoryId,
Product => Product.CategoryId,
(x, y) => new { Category = x, Products = y })
.SelectMany(
xy => xy.Products.DefaultIfEmpty(),
(x, y) => new { Category = x.Category, Product = y })
.Where(w => w.Product.CategoryId == null)
.Select(s => new { Category = s.Category});发布于 2013-03-27 19:01:40
你可以像下面这样写和划分你的查询,这样可以很容易地解决你的问题。
另请查看我的帖子:SQL to LINQ ( Case 7 - Filter data by using IN and NOT IN clause)
//first do the union of two
var query = ((from d in LmsEventMatch
where d.EventId == 1
select d.TeamHomeId).
Union(from e in LmsEventMatch
where e.EventId == 1
select e.TeamAwayId));
//than perform !contains operation for no in
var records =( from t in LmsTeams
join g in Games on t.GameId equals g.Id
where t.GameId == 1 && t.Active == true && !query.Contains(t.Id)
select t).ToList();in和not in - linq查询的图形表示

对于从sql到linq的转换,可以使用:Linqer

https://stackoverflow.com/questions/15657086
复制相似问题