What is the best/easiest way to configure AutoMapper to map ICollection<DomainModel> to ICollection<ViewModel> to ICollection<object>?
I have a DomainModel which looks like this:
public class DomainModel
{
ICollection<EFEntity> Data;
//other stuff
}
I want to map this DomainModel to an MVC ViewModel:
public class ViewModelWithCollection
{
ICollection<object> Data;
//other stuff
}
I need ICollection<object> because I use the following View:
@model ViewModelWithCollection
<table>
@foreach(object x in Model.Data)
{
Html.Partial("PartialView", x)
}
</table>
For each concrete ViewModel there exists a PartialView like this:
@model ViewModel
<tr> <!-- Render specific View Data --> <tr>
When I use
AutoMapper.Map<DomainModel, ViewModelWithCollection>(source, target);
AutoMapper just makes something like this:
object target = (object)EFEntity
which of course won't work.
After some hours of searching i found out that the thing i want to achieve is called Mapping Inheritance: https://github.com/AutoMapper/AutoMapper/wiki/Mapping-inheritance
So the solution to my problem is
AutoMapper.Map<DomainModel, ViewModelWithCollection>();
AutoMapper.Map<EFEntity, object>()
.Include<EFEntity, ViewModel>();
AutoMapper.Map<EFEntity, ViewModel>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With