Linq使用左外连接生成非预期的sql

时间:2014-02-20 19:44:44

标签: c# sql sql-server linq

我有一个linq语句,它应该产生一个通用的左外连接(特别是使用空值)但是它产生了一个奇怪的sql,它也使用了count(*)

这是linq:

(from ccc in cDataContext.CategoryCountryCategoryTypeMappings
 join cl in currentLogs on ccc.CategoryCountryCategoryTypeMappingID equals
 cl.CategoryCountryCategoryTypeMappingID 
 into final
 select final);

当前日志如下所示:

 (from dll in cDataContext.DownloadLogs
  where dll.DTS.Hour == DateTime.Now.Hour && dll.DTS.Date== DateTime.Now.Date
  select dll)

输出sql变为:

 SELECT [t1].[LogId], [t1].[CategoryCountryCategoryTypeMappingID], [t1].[CaptureTime], [t1].[Response], [t1].[DTS], [t1].[DLID], (
    SELECT COUNT(*)
    FROM clients.[dbo].[DownloadLog] AS [t2]
    WHERE ([t0].[CategoryCountryCategoryTypeMappingID] = [t2].[CategoryCountryCategoryTypeMappingID]) 
) AS [value]
FROM clients.[Store].[CategoryCountryCategoryTypeMappings] AS [t0]
LEFT OUTER JOIN clients.[dbo].[DownloadLog] AS [t1] ON ([t0].[CategoryCountryCategoryTypeMappingID] = [t1].[CategoryCountryCategoryTypeMappingID])
ORDER BY [t0].[CategoryCountryCategoryTypeMappingID], [t1].[LogId]

我在寻找什么:

SELECT * FROM 
clients.[Store].[CategoryCountryCategoryTypeMappings] AS [t0]
LEFT INNER JOIN clients.[dbo].[DownloadLog] AS [t1] 
ON ([t0].[CategoryCountryCategoryTypeMappingID] = [t1].[CategoryCountryCategoryTypeMappingID])

我如何生成所需的sql?

1 个答案:

答案 0 :(得分:1)

MSDN具有良好的linq示例。 http://msdn.microsoft.com/en-US/vstudio/ee908647.aspx

对于左外连接:

var q = 
    from c in categories 
    join p in products on c equals p.Category into ps 
    from p in ps.DefaultIfEmpty() 
    select new { Category = c, ProductName = p == null ? "(No products)" : p.ProductName };