配置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
当然不会奏效。
答案 0 :(得分:3)
经过几个小时的搜索,我发现我想要实现的东西叫做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>();
答案 1 :(得分:2)
我遇到了同样的问题。
我有我的域名模型:
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))