【发布时间】: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