【问题标题】:Select values from two tables using “WHERE NOT IN” and DISTINCT in LINQ in Linq to Sql在 Linq to Sql 的 LINQ 中使用“WHERE NOT IN”和 DISTINCT 从两个表中选择值
【发布时间】:2016-06-14 11:23:00
【问题描述】:

我有两个像 CustomerVisitDetail 的表,我需要将 SQL Query 下面转换成 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

【问题讨论】:

  • 请不要只发布 SQL 并要求转换。至少显示一个类模型,以便导航属性和关联的多样性是可见的。此外,请说明您的目标是什么类型的 LINQ(针对实体?针对 SQL,它们不一样!),展示您自己的初步努力。他们向我们解释的内容比您想象的要多。

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


【解决方案1】:

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很有帮助

【讨论】:

    猜你喜欢
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多