。包含在下面的查询中不包含真的

时间:2013-01-09 09:55:25

标签: entity-framework include

var diaryEntries = (from entry in repository.GetQuery<OnlineDiary.Internal.Model.DiaryEntry>()
                               .Include("DiaryEntryGradeChangeLog")
                               .Include("DiaryEntryAction")
                                           join diary in repository.GetQuery<OnlineDiary.Internal.Model.OnlineDiary>()                                           
                                           on entry.DiaryId equals diary.Id
                                           group entry
                                           by diary
                                           into diaryEntriesGroup
                                           select new { Diary = diaryEntriesGroup.Key,
                                               DiaryEntry = diaryEntriesGroup.OrderByDescending(diaryEntry => diaryEntry.DateModified).FirstOrDefault(),
                                           });

此查询不包含“DiaryEntryGradeChangeLog”和“DiaryEntryAction”导航属性,此查询有什么问题?

我已从查询中删除了联接,并按照以下方式进行了更正,但仍然没有填充任何内容

var diaryEntries = from entry in repository.GetQuery<OnlineDiary.Internal.Model.DiaryEntry>()
                                   .Include("DiaryEntryGradeChangeLog").Include("DiaryEntryAction")
                                   .Where(e => 1 == 1)
                                       group entry
                                       by entry.OnlineDiary
                                       into diaryEntryGroups
                                       select 
                                       new { DiaryEntry = diaryEntryGroups.OrderByDescending(diaryEntry => diaryEntry.DateModified).FirstOrDefault() };

1 个答案:

答案 0 :(得分:1)

不会。 Include仅在查询形状未发生变化时(按设计)才有效。如果您使用此查询,它将起作用,因为查询的形状仍然相同(OnlineDiary.Internal.Model.DiaryEntry):

var diaryEntries = (from entry in repository.GetQuery<OnlineDiary.Internal.Model.DiaryEntry>()
                           .Include("DiaryEntryGradeChangeLog")
                           .Include("DiaryEntryAction");

但是,一旦您使用手动加入,分组或投影(select new { }),您就更改了查询的形状,并且会跳过所有Include次调用。

编辑:

您必须使用此类内容(未经测试)才能获取相关数据:

var diaryEntries = from entry in repository.GetQuery<OnlineDiary.Internal.Model.DiaryEntry>()
                   group entry by entry.OnlineDiary into diaryEntryGroups
                   let data = diaryEntryGroups.OrderByDescending(diaryEntry => diaryEntry.DateModified).FirstOrDefault()
                   select new { 
                       DiaryEntry = data,
                       GradeChangeLog = data.DiaryEntryGradeChangeLog,
                       Action = data.DiaryEntryAction
                   };

或任何类似的查询,其中您手动将投影中的关系属性填充为匿名或未映射类型。