在连接中检索整个对象而不仅仅是属性

时间:2011-03-15 16:35:45

标签: linq entity-framework-4 linq-to-entities poco

无论如何,我可以获得整个对象平台而不仅仅是此查询中的属性,我正在使用Poco和EF4:

var games = (from g in ctx.Games
join p in ctx.Platforms on g.Platform.Id equals p.Id into joinTable
from j in joinTable.DefaultIfEmpty()                             
  select new
     {
       GameId = g.Id,
       Title = g.Title,
       PlatformId = j.Id,
       PlatformShort = j.Platform_short                                 

      });

我只想检索整个Platform对象(j),而不是使用PlatformId和PlatformShort。比如“Platform = j”

有没有更好的方法来返回一个类型化的集合,而不是首先迭代游戏?

foreach (var g in games)
            {
                Game game = new Game();
                game.Platform = new Platform();
                game.Id = g.GameId;
                game.Title = g.Title;
                game.Platform.Id = g.PlatformId;
                game.Platform.Platform_short = g.PlatformShort;                    

                col.Add(game);
            }

我尝试了这个:

  

返回   。ctx.Games.Include( “平台”)采取(50).ToList();

现在我对所有100条记录都有相同的价值。

这是SQL:

FROM   [dbo].[Games] AS [Extent1] 
LEFT OUTER JOIN  (SELECT [Extent2].[Id] AS [Id1], [Extent2].[Platform_short] AS [Platform_short], [Extent2].[Platform_long] AS [Platform_long], [Extent2].[Description] AS [Description], [Extent2].[Image] AS [Image], [Extent2].[CreatedDate] AS [CreatedDate1], [Extent2].[ModifiedDate] AS [ModifiedDate1]
    FROM  [dbo].[Platforms] AS [Extent2]
    LEFT OUTER JOIN [dbo].[Games] AS [Extent3] ON [Extent2].[Id] = [Extent3].[PlatformId] ) AS [Join1] ON [Extent1].[PlatformId] = [Join1].[Id1] LEFT OUTER JOIN  (SELECT [Extent4].[Id] AS [Id3], [Extent5].[Id] AS [Id2]
    FROM  [dbo].[Platforms] AS [Extent4]
    LEFT OUTER JOIN [dbo].[Games] AS [Extent5] ON [Extent4].[Id] = [Extent5].[PlatformId] ) AS [Join3] ON [Extent1].[PlatformId] = [Join3].[Id3]

1 个答案:

答案 0 :(得分:0)

是的,有更好的方法:

var collection = context.Games.Include("Platform").ToList();