在复杂查询中,实体框架中的急切加载失败

时间:2009-09-17 19:13:32

标签: entity-framework linq-to-entities eager-loading

以下查询在执行时无法加载表:

IEnumerable<Bookmark> tempBookmarks = ListBookmarksByUserID(userID);
IEnumerable<CandidateWithBookmarks> results = (from c in _internshipEntities.CandidateSet
                                            .Include("education")
                                            .Include("progress")
                                            .Include("contacts")
                                            .Include("availability")
                                            .Include("hosttypes")
                                            .Include("hostsizes")
                                            .Include("hostcapacities")
                                            .Include("hoststates")
                                            .Include("users")
                       join b in tempBookmarks on c.ID equals b.candidates.ID
                       select new CandidateWithBookmarks()
                                  {CandidateObject = c, BookmarkObject = b});
return results;

我找到了一些与此问题相关的文章,即Alex James' article "How to make Include really Include"。解决方案有一点需要注意:

  

为此,您的最终选择必须是实体,即选择帖子而不是选择新的{...}

这显然是上述代码块的问题。是否有任何其他已知的解决此问题的解决方案不会破坏急切的加载?

1 个答案:

答案 0 :(得分:2)

我认为我解决了这个问题,但它可能仅适用于此特定实例,通过在连接后移动包含,查询似乎有效:

IEnumerable<CandidateWithBookmarks> results = (
    from b in tempBookmarks
    join c in _internshipEntities.CandidateSet
                                 .Include("education")
                                 .Include("progress")
                                 .Include("contacts")
                                 .Include("availability")
                                 .Include("hosttypes")
                                 .Include("hostsizes")
                                 .Include("hostcapacities")
                                 .Include("hoststates")
                                 .Include("users")
    on b.candidates.ID equals c.ID
    select new CandidateWithBookmarks(){CandidateObject = c, BookmarkObject = b});

编辑:我有类似的另一个查询也需要一个外部联接,这会产生一些问题,因为它会影响你加入什么,不像这个例子,但它仍然可行。