2012-03-16 393 views
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吗?

回答

-1

你应该看看通过Linq2Sql的渴望加载。例如,看到这个博客: http://www.lowendahl.net/showShout.aspx?id=190

看来,有一些问题,但它应该在gerenal工作。

其实,如果有可能,我会建议转移到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(); 
+0

如果你读了文章链接,你就不会说“用预先加载”,因为在L2S预先加载不那么渴望 - 只1级下降。事情是我需要2个或更多的关卡。英孚不是一种选择 - 这是我维护的某种遗留系统。 – rafek 2012-03-16 15:39:33

+0

我看过这篇文章,现在我说有限制。我至少给了你看点的地方。 – 2012-03-17 16:55:50