在Linq to Sql中使用“WHERE NOT IN”和LINQ中的DISTINCT从两个表中选择值

时间:2016-06-14 11:23:01

标签: sql entity-framework linq linq-to-sql linq-to-entities

我有两个表,如客户 VisitDetail ,我需要将 SQL查询转换为 Linq to Sql

select *
from Customer
where id not in (select distinct CustomerId
                 from visitdetail
                 where VisitDate='2016-06-13' and SalesRepAccId=1 and
                       RouteId=10
                ) and
      RouteId = 10 and Active=1 and SalesRepAccId=1

1 个答案:

答案 0 :(得分:0)

如果对NOT IN子句进行嵌套查询,请使用 !Contains()

var customerVisitDetails = (from row in db.Visitdetail
                            where row.VisitDate == '<add obj for date comparison>'
                            && row.SalesRepAccId == 1 && row.RouteId == 10
                            select row.CustomerId).Distinct().ToList();

var output = (from c in db.Customer
              where !customerVisitDetails.Contains(c.Id)
              && c.RouteId == 10 && c.Active == 1 && c.SalesRepAccId == 1
              select c);

此外,这对starting with LinQ

非常有帮助