【问题标题】:Mapping Linq-to-SQL classes to domain classes with nested collections使用嵌套集合将 Linq-to-SQL 类映射到域类
【发布时间】:2023-04-02 11:46:01
【问题描述】:

我有以下映射函数:

 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?

【问题讨论】:

    标签: c# linq linq-to-sql


    【解决方案1】:

    您应该查看通过 Linq2Sql 进行预加载。例如,请参阅此博客: http://www.lowendahl.net/showShout.aspx?id=190

    看起来,有一些问题,但它应该可以正常工作。

    实际上,如果可能的话,我会建议转移到 EntityFramework。现在 LINQ2SQL 是一项遗留技术。特别是,EF 通过使用简单的Include() 方法对预加载有很好的支持,如下所示:

    _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();
    

    【讨论】:

    • 如果您阅读链接文章,您不会说“使用急切加载”,因为 L2S 中的急切加载并不那么急切——只有 1 级。问题是我需要降低 2 个或更多级别。 EF 不是一个选项 - 它是我维护的某种遗留系统。
    • 我读了这篇文章,我现在知道有限制。我至少给了你看的地方。
    猜你喜欢
    • 2010-11-26
    • 1970-01-01
    • 2010-11-23
    • 2022-11-14
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多