如何在EF獲取數據並使用Automapper將其映射時對兒童運行查詢?如何在兒童中添加where子句並將其正確映射
讓我首先解釋一下情景,我有一個父母和孩子,他們都可以是活動的或不活動的。如果父母不活躍,則所有孩子都不活動,如果父母活躍,則一些孩子可以活躍或不活躍。 現在這個返回與孩子
return Mapper.Instance.Map<ObservableCollection<Parent>>(context.Parent.AsNoTracking().ProjectTo<ParentDTOWithChildren>(Mapper.Configuration));
父現在,這是我後,用活潑的孩子只有
Mapper.Instance.Map<ObservableCollection<Parent>>(context.Parent.AsNoTracking()
.Where(p => p.IsInactive != true)
.Select(parent => new
{
parent,
Children = parent.Children.Where(c => c.IsInactive != true)
})
.ProjectTo<ParentDTOWithChildren>(Mapper.Configuration));
第二次嘗試產生正確的SQL查詢返回活躍的父母,但是映射呢沒有正確映射,孩子們得到所有的值,但父母沒有。 我發現,如果我手動選擇每個屬性,然後,家長得到的所有屬性,所以此工程
Mapper.Instance.Map<ObservableCollection<Parent>>(context.Parent.AsNoTracking()
.Where(p => p.IsInactive != true)
.Select(parent => new
{
parent.Id,
parent.Description,
parent.Information,
. . .
Children = parent.Children.Where(c => c.IsInactive != true)
})
.ProjectTo<ParentDTOWithChildren>(Mapper.Configuration));
理想情況下,我想只選擇父(使用中間的例子),它應該知道如何映射它,但是直到我指定了每個我想要的屬性。映射配置是正確完成的,因爲第一個例子工作得很好,有沒有更好的方法來選擇(映射)從該匿名類型到我的DTO的所有屬性?
非常感謝。
編輯
這是使它工作,而不是匿名類型的選擇的
服務來獲取數據。
Mapper.Instance.Map<ObservableCollection<Parent>>
(context.Parent.AsNoTracking().Where(p => p.IsInactive != true)
.ProjectTo<ParentDTOWithChildren>(Mapper.Configuration, new {excludeInactive = true}));
映射
var excludeInactive = false;
CreateMap<Parent, ParentDTOWithChildren>()
.ForMember(p => p.Children, opt => opt.MapFrom(parent => parent.Children.Where(child => !excludeInactive || child.IsInactive != true)))
.ReverseMap();
發佈示例類和AM配置可能會有所幫助。 –