我想創建一個映射爲一個有點複雜的實體模型展平視圖模型解決使用AutoMapper
我的實體模型,像這樣
cbItems
has many cbItemsContent
has many cbRegulators
所以我的ViewModels複雜的實體模型,平面模型視圖是像這樣
爲cbItems:
public class ItemViewModel
{
public ItemViewModel()
{
this.CbItemsContents = new HashSet<ItemContentViewModel>();
}
public int ItemID { get; set; }
......
public virtual ICollection<ItemContentViewModel> CbItemsContents { get; set; }
}
}
爲cbItemsContent:
public class ItemContentViewModel
{
public int ItemContentID { get; set; }
public int ItemID { get; set; }
....
public ItemContentRegulatorsViewModel RegulatedBy { get; set; }
}
}
爲cbRegulators:
public class ItemContentRegulatorsViewModel
{
public int ItemContentId { get; set; }
public IEnumerable<int> RegulatorIds { get; set; }
}
}
我曾希望這將是那麼容易,因爲這樣的:
config.CreateMap<CbItem, ItemViewModel>();
config.CreateMap<CbItemsContent, ItemContentViewModel>()
.ForMember(dest => dest.RegulatedBy.ItemContentId,
m => m.MapFrom(src => src.GenericID))
.ForMember(dest => dest.RegulatedBy.RegulatorIds,
n => n.MapFrom(src => src.cbItemsContentRegulators.Select(q => q.cbRegulator.RegulatorId)));
從格蘭以下查詢
:
ItemViewModel item =
_context.cbItems.Where(u => u.ItemId = id)
.ProjectTo<ItemViewModel>()
.first();
但這個結果在一個錯誤:
Expression 'dest => dest.RegulatedBy.ItemContentId' must resolve to top-level member and not any child object's properties. Use a custom resolver on the child type or the AfterMap option instead. Parameter name: lambdaExpression
我怎樣才能實現我想要的模型佈局?
那實際上什麼我有,我是缺少」 .ForMember(DEST => dest.RegulatedBy,O => o.MapFrom(SRC => SRC ));」爲第一個地圖。我不確定我是否理解這條線上發生的事情,你能否擺脫任何光線?我不知道什麼REgulatedBy被映射到(src => src) –
它基本上告訴AutoMapper RegulatedBy(意義類型「ItemContentRegulatorsViewModel」)將被映射到源(意思是'CbItemsContent'),因此它會尋找一個從'CbItemsContent'映射到'ItemContentRegulatorsViewModel' - 它定義如下 –