将Linq-to-SQL类映射到具有嵌套集合的域类

时间:2012-03-16 11:22:22

标签: c# linq linq-to-sql

我遵循映射功能:

 private static Expression<Func<ActionComment, Domain.ActionComment>> MapActionComment =
      actionComment => new Domain.ActionComment
      {
        Id = actionComment.Id,
        Comment = actionComment.Comment,
      };

    private static Expression<Func<Action, Domain.Action>> MapAction =
      action => new Domain.Domain
      {
        Id = action.Id,
        Comments = action.ActionComments
                         .Select(ac => MapActionComment.Invoke(ac))
      };

    private static Expression<Func<Nc, Domain.Nc>> MapNc =
      nc => new Domain.Nc
              {
                Id = nc.Id,
                Actions = nc.Actions
                            .Select(a => MapAction.Invoke(a)),
              };

以下Linq-to-SQL查询:

_ctx.NCs
  .Where(n => n.Id == id)
  .Select(MapNc)
  .SingleOrDefault();

生成的SQL语句是:

SELECT [t0].[Id], -- columns  
    (SELECT COUNT(*)
    FROM [dbo].[Actions] AS [t2]
    WHERE [t2].[NCId] = [t0].[Id]
    ) AS [value]
FROM [dbo].[NCs] AS [t0]
LEFT OUTER JOIN [dbo].[Actions] AS [t1] ON [t1].[NCId] = [t0].[Id]
WHERE [t0].[Id] = @p0
ORDER BY [t0].[Id], [t1].[Id]

问题是Action对象的Comments集合没有加载它的内容(它直到实际使用集合为止)。

有没有办法强制Linq-to-SQL生成 ONE 单个语句,该语句将获取Ncs,Actions和ActionComments?

1 个答案:

答案 0 :(得分:-1)

你应该看看通过Linq2Sql的急切加载。例如,请参阅此博客: http://www.lowendahl.net/showShout.aspx?id=190

看来,存在一些问题,但它应该在gerenal中起作用。

实际上,如果有可能,我建议转到EntityFramework。现在LINQ2SQL是一项传统技术。特别是,通过使用简单的Include()方法,EF可以很好地支持预先加载:

_ctx.NCs
   .Where(n => n.Id == id)
   .Select(MapNc)
   .Include(nc => nc.Comments)   //EF to eager load relation
   .Include(nc => nc.Actions)   //EF to eager load relation
   .SingleOrDefault();