2
我下面的映射函数:映射LINQ到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到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吗?
如果你读了文章链接,你就不会说“用预先加载”,因为在L2S预先加载不那么渴望 - 只1级下降。事情是我需要2个或更多的关卡。英孚不是一种选择 - 这是我维护的某种遗留系统。 – rafek 2012-03-16 15:39:33
我看过这篇文章,现在我说有限制。我至少给了你看点的地方。 – 2012-03-17 16:55:50