c# – 使用实体框架进行预测
发布时间:2020-12-15 21:36:28 所属栏目:百科 来源:网络整理
导读:我有一个关于使用实体框架进行预测的问题. 我有三张桌子: 简介,传记和传记翻译 我想做以下投射:(传记= IQueryable) return biographies.Select(b = new ProfileBiography { Id = b.BiographieID,OwnerId = b.Profile.ProfileID,Translations = b.Translatio
我有一个关于使用实体框架进行预测的问题.
我有三张桌子: 我想做以下投射:(传记= IQueryable) return biographies.Select(b => new ProfileBiography { Id = b.BiographieID,OwnerId = b.Profile.ProfileID,Translations = b.Translations.Select(t => new DocumentTranslation() { DocumentId = b.BiographieID,FileName = t.BiographyTextFile,Title = t.Title,Text = t.Text,LanguageId = t.LanguageID }) } 我的问题: 投影不适用于集合属性吗? 我也尝试过传记.Inlcude(“翻译”),但结果是一样的. UPDATE 我在这里创建了一个小型测试项目: TestProject.zip 只有3个表(包括创建和插入语句),EDMX文件和加载传记的类.我仍然无法让它工作来投射集合导航属性,简单的导航属性工作正常.也许有人可以从测试项目中看到我做错了什么…… UPDATE 我尝试了一种新方法,但仍然没有运气: using (var context = new DatabaseEntities()) { return context.BiographySets .Where(bio => bio.ProfileId == profileId) .Select(bio => new DocumentModel() { Id = bio.Id,OwnerId = bio.Profile.Id,Translations = context.BiographyTranslationSets.Where(t => t.BiographyId == bio.Id) .Select(t => new DocumentTranslation() { DocumentId = bio.Id,LanguageId = t.LanguageId,Text = t.Text }) }).ToList(); } UPDATE 如果我使用匿名类型,它会令人惊讶地工作…… using (var context = new DatabaseEntities()) { return context.BiographySets .Where(bio => bio.ProfileId == profileId) .Select(bio => new { Id = bio.Id,Translations = bio.Translations .Select(t => new { DocumentId = bio.Id,Text = t.Text }) }).ToList(); } 解决方法
好的,我发现了问题:
这是我的DocumentModel类: public class DocumentModel { public DocumentModel() { _translations = new List<DocumentTranslation>(); } public int Id { get; set; } public int OwnerId { get; set; } private List<DocumentTranslation> _translations; public IEnumerable<DocumentTranslation> Translations { get { return _translations; } set { _translations = value.ToList(); } } } 这是问题所在: set { _translations = value.ToList(); } 我无法在我的Setter中调用ToList(),因为它会破坏查询. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |