实体框架代码首先一对多做错查询?

时间:2011-05-05 08:41:37

标签: entity-framework linq-to-entities ef-code-first code-first entity-framework-4.1

所以我有一个模特

public class Player
{
    public int PlayerId { get; set; }

    [Required]
    public string Name2 { get; set; }

    public string Cv { get; set; }

    public int TeamId { get; set; }
    public virtual Team Team { get; set; }
}



public class Team
{
    public int TeamId { get; set; }
    [Required]
    public string Name { get; set; }
    public string City { get; set; }
    public DateTime Founded { get; set; }

    public virtual IList<Player> Players { get; set; }
}

数据库中的我的团队表包含记录,数据库中的我的玩家表不包含任何(空)。

当我运行此查询时:

        IQueryable<Player> query = playerRepository.All.Include(p => p.Team);

        return View((query);

我在DB(通过探查器)获得此查询:

SELECT 
[Project1].[TeamId] AS [TeamId], 
[Project1].[Name] AS [Name], 
[Project1].[City] AS [City], 
[Project1].[Founded] AS [Founded], 
[Project1].[C1] AS [C1], 
[Project1].[PlayerId] AS [PlayerId], 
[Project1].[Name2] AS [Name2], 
[Project1].[Cv] AS [Cv], 
[Project1].[TeamId1] AS [TeamId1]
FROM (  SELECT 
            [Limit1].[TeamId] AS [TeamId], 
            [Limit1].[Name] AS [Name], 
            [Limit1].[City] AS [City], 
            [Limit1].[Founded] AS [Founded], 
            [Extent2].[PlayerId] AS [PlayerId], 
            [Extent2].[Name2] AS [Name2], 
            [Extent2].[Cv] AS [Cv], 
            [Extent2].[TeamId] AS [TeamId1], 
            CASE    WHEN ([Extent2].[PlayerId] IS NULL) THEN CAST(NULL AS int) 
                    ELSE 1 
            END AS [C1]
        FROM   (    SELECT TOP (10) [c].[TeamId] AS [TeamId], 
                                    [c].[Name] AS [Name], 
                                    [c].[City] AS [City], 
                                    [c].[Founded] AS [Founded]
                      /* HERE */    
                      FROM [dbo].[Teams] AS [c] 
                ) AS [Limit1]
        /* AND HERE */
        LEFT OUTER JOIN [dbo].[Players] AS [Extent2] 
        ON              [Limit1].[TeamId] = [Extent2].[TeamId]
)  AS [Project1]
ORDER BY [Project1].[TeamId] ASC, [Project1].[C1] ASC

结果我在屏幕上显示一个空行。这是因为这些联接是以错误的顺序完成的......我没有加入Teams on Players,而是让玩家加入了团队...这反过来意味着即使我在DB中没有玩家,我也会得到一个空行。网格。

任何人都有任何想法???

弗拉丹

1 个答案:

答案 0 :(得分:3)

你必须做错事或者你正在查看错误的查询。我使用了你的实体和你的linq查询:

var data = context.Players.Include(p => p.Team).ToList();

我得到了这个SQL查询:

SELECT 
[Extent1].[PlayerId] AS [PlayerId], 
[Extent1].[Name2] AS [Name2], 
[Extent1].[Cv] AS [Cv], 
[Extent1].[TeamId] AS [TeamId], 
[Extent2].[TeamId] AS [TeamId1], 
[Extent2].[Name] AS [Name], 
[Extent2].[City] AS [City], 
[Extent2].[Founded] AS [Founded]
FROM  [dbo].[Players] AS [Extent1]
INNER JOIN [dbo].[Teams] AS [Extent2] ON [Extent1].[TeamId] = [Extent2].[TeamId]

但是如果我使用这个查询:

var data = context.Teams.Include(t => t.Players).Take(10).ToList();

我将准确地获取您的SQL查询。 TOP (10)和反向表格查询不会毫无理由地出现。