![](/img/trans.png)
[英]Map ICollection<Model> to List<ViewModel> using AutoMapper
[英]Map from ICollection<EFEntity> to ICollection<ViewModel> to ICollection<Object> with AutoMapper
配置AutoMapper以將ICollection<DomainModel>
映射到ICollection<ViewModel>
到ICollection<object>
的最佳/最簡單方法是什么?
我有一個DomainModel,如下所示:
public class DomainModel
{
ICollection<EFEntity> Data;
//other stuff
}
我想將此DomainModel映射到MVC ViewModel:
public class ViewModelWithCollection
{
ICollection<object> Data;
//other stuff
}
我需要ICollection<object>
因為我使用以下View:
@model ViewModelWithCollection
<table>
@foreach(object x in Model.Data)
{
Html.Partial("PartialView", x)
}
</table>
對於每個具體的ViewModel,都存在這樣的PartialView:
@model ViewModel
<tr> <!-- Render specific View Data --> <tr>
我用的時候
AutoMapper.Map<DomainModel, ViewModelWithCollection>(source, target);
AutoMapper就是這樣的:
object target = (object)EFEntity
這當然行不通。
經過幾個小時的搜索,我發現我想要實現的東西叫做Mapping Inheritance: https : //github.com/AutoMapper/AutoMapper/wiki/Mapping-inheritance
所以我的問題的解決方案是
AutoMapper.Map<DomainModel, ViewModelWithCollection>();
AutoMapper.Map<EFEntity, object>()
.Include<EFEntity, ViewModel>();
AutoMapper.Map<EFEntity, ViewModel>();
我有似乎是同樣的問題。
我有我的域名模型:
public class Client
{
public int ClientId { get; set; }
public virtual ICollection<Contract> Contracts { get; set; }
}
我的視圖模型:
public class ClientProfileViewModel
{
public int ClientId { get; set; }
public IEnumerable<ContractProfileViewModel> Contracts { get; set; }
}
然后在我的映射中:
Mapper.CreateMap<Client, ClientProfileViewModel>()
.ForMember(c => c.Contracts, options => options.MapFrom(c => c.Contracts));
Mapper.CreateMap<ClientProfileViewModel, Client>()
.ForMember(c => c.Contracts, options => options.MapFrom(c => c.Contracts))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.