将此SQL语句转换为LINQ

时间:2011-05-19 13:08:39

标签: c# sql linq linq-to-sql

我对linq很新,我在LINQ中有效地编写这个查询时遇到了一些困难。

SELECT ID, UniqueID, RouteHeaderID, RouteObjectState, OriginalRouteUniqueID
FROM  dbo.MeterReadingOrderERPRouteCreateResponses
WHERE (ID NOT IN (SELECT MeterReadingOrderERPRouteCreateResponseID
                  FROM  dbo.Tasks
                  WHERE (TaskType = 'MeterReading')))

有什么帮助吗?我尝试过这样的解决方案:How would you do a "not in" query with LINQ?但是收到以下错误:无法创建类型'TaskManager.Models.Task'的常量值。在此上下文中仅支持原始类型(例如Int32,String和Guid')。

2 个答案:

答案 0 :(得分:3)

只是做到这一点,但也许这个?

var subQuery = from t in Tasks
               where t.TaskType == "MeterReading"
               select t.MeterReadingOrderERPRouteCreateResponseID

var query = from m in MeterReadingOrderERPRouteCreateResponses
            where !subQuery.Contains(m.ID)
            select new
            {
                ID = m.ID,
                UniqueID = m.UniqueID,
                RouteHeaderID = m.RouteHeaderID,
                RouteObjectState = m.RouteObjectState,
                OriginalRouteUniqueID = m.OriginalRouteUniqueID
            };

答案 1 :(得分:2)

var meterReadingTasks = from task in context.Tasks
                       where task.TaskType == "MeterReading"
                       select task.MeterReadingOrderERPRouteCreateResponseID;

var results = from m in context.MeterReadingOrderERPRouteCreateResponses
              where !meterReadingTasks.Contains(m.Id)
              select new { m.ID, m.UniqueID, m.RouteHeaderID, m.RouteObjectState, m.OriginalRouteUniqueID};