Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map from ICollection<EFEntity> to ICollection<ViewModel> to ICollection<Object> with AutoMapper

Tags:

c#

automapper

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.

like image 709
Dresel Avatar asked Dec 08 '25 07:12

Dresel


1 Answers

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>();
like image 198
Dresel Avatar answered Dec 09 '25 23:12

Dresel