0

我有以下 SQL 查询,并想转换为 LINQ to SQL,我将在实体框架 5.0 中使用它

var internationalDesksList =
            from internationalDesks in _context.InternationalDesks
            from subsection in
                _context.Subsections.Where(
                    s =>
                    internationalDesks.EBALocationId == s.LocationId ||
                    internationalDesks.FELocationId == s.LocationId).DefaultIfEmpty()
            where subsection.PublicationId == 1

            select new {internationalDesks.Id, subsection.LocationId};

我已经提到了以下帖子和答案。虽然没有运气。

当我在LINQPad中尝试这个查询时, 我得到了以下正确的答案。

-- Region Parameters
DECLARE @p0 Int = 1
-- EndRegion
SELECT [t0].[Id], [t1].[Id] AS [Id1]
FROM [InternationalDesks] AS [t0]
LEFT OUTER JOIN [Subsection] AS [t1] ON (([t0].[FELocationId]) = [t1].[LocationId]) OR (([t0].[EBALocationId]) = [t1].[LocationId])
WHERE [t1].[PublicationId] = @p0

但是在实体框架 5 ( DBContext ) 中,它没有为我提供正确的查询。当我签入 SQL 探查器时,子节表中的所有列都被选中。而已。

结果如下:

SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[Description] AS [Description], 
[Extent1].[PracticeAreaId] AS [PracticeAreaId], 
[Extent1].[LocationId] AS [LocationId], 
...
FROM [dbo].[Subsection] AS [Extent1]

不知道可能是什么问题。请帮我。

4

1 回答 1

0

使用 LINQ,您不能对某些布尔表达式执行 LEFT OUTER JOIN,仅支持等值连接。因此,您可以通过这种方式生成 CROSS JOIN:

var internationalDesksList =
            from internationalDesks in _context.InternationalDesks
            from subsection in _context.Subsections
            where subsection.PublicationId == 1 &&
                  (internationalDesks.EBALocationId == subsection.LocationId ||
                   internationalDesks.FELocationId == subsection.LocationId)
            select new {
                internationalDesks.Id, 
                subsection.LocationId
            };

EF 5 将生成以下 SQL:

SELECT 
[Extent1].[Id] AS [Id], 
[Extent2].[LocationId] AS [LocationId]
FROM  [dbo].[InternationalDesks] AS [Extent1]
CROSS JOIN [dbo].[Subsections] AS [Extent2]
WHERE (1 = [Extent2].[PublicationId]) AND 
      ([Extent1].[EBALocationId] = [Extent2].[LocationId] OR 
       [Extent1].[FELocationId] = [Extent2].[LocationId])

如您所见,仅选择了必需的列。我还在 LINQ to SQL 中检查了这个查询 - 生成了以下查询:

DECLARE @p0 Int = 1

SELECT [t0].[Id], [t1].[LocationId]
FROM [InternationalDesks] AS [t0], [Subsections] AS [t1]
WHERE ([t1].[PublicationId] = @p0) AND 
      (([t0].[EBALocationId] = [t1].[LocationId]) OR 
       ([t0].[FELocationId] = [t1].[LocationId]))
于 2013-06-21T15:10:24.180 回答