配置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>
,因为我使用以下视图:
@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
这当然是行不通的。
经过几个小时的搜索,我发现我想要实现的东西叫做映射继承: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))