【问题标题】:Retrieve whole object in a join instead of just properties在连接中检索整个对象,而不仅仅是属性
【发布时间】:2011-03-15 16:35:45
【问题描述】:

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

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。像“平台 = 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("平台").Take(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]

【问题讨论】:

  • 您的应用程序有问题,因为使用 Platform = j 应该可以工作。

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


【解决方案1】:

是的,有更好的方法:

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

【讨论】:

  • 当我使用您的方法时,我收到此错误:当没有数据存在时尝试读取无效。有什么想法吗?
  • 您的模型是如何定义的。 Platform 导航属性是否在 Game 上?如果是,这必须有效,而且这是正确的方法。
  • 是平台是游戏上的导航属性。也许要处理的数据太多了?我得到了大约 30000 多条记录。
  • 当我调试它时,它会在这一点停止: IList test = ctx.Games.Include("Platform").ToList();并且不返回任何东西。我的电脑开始努力工作了!
  • 将异常的堆栈跟踪添加到您的问题中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-09
  • 1970-01-01
  • 2018-11-21
  • 2018-05-03
  • 1970-01-01
  • 2019-03-05
相关资源
最近更新 更多