Asp.net c # DDD - problem passing data from Entity to ViewModel

0

I'm developing an ASP.NET MVC project, with DDD structure and using Simple Injector. I can perform persistence in BD normally, but at the moment of retrieving the information and displaying it in a list, it presents the following error message.

  

The template item entered in the dictionary is from   type 'System.Collections.Generic.List 1[Domain.Entities.SistemaEntities]', mas esse dicionário requer um item do tipo 'System.Collections.Generic.IEnumerable 1 [View.Models.SystemViewModel]'.

This is the control that is calling the method for searching the information:

public ActionResult Index()
        {
            var resultado = _SistemaDominio.GetAll().AsEnumerable();
            return View(resultado);                 
        }

And this is the page that lists.

@model IEnumerable<View.Models.SistemaViewModel>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Insert")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.CodSistema)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Nome)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Descricao)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.DTCadastro)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Status)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.CodSistema)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Nome)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Descricao)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.DTCadastro)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Status)
        </td>
        <td>
            @Html.ActionLink("Edit", "Update", new { id=item.IDSistema }) |
            @Html.ActionLink("Details", "Details", new { id=item.IDSistema }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.IDSistema })
        </td>
    </tr>
}

</table>

Domain.Service class

public IList<SistemaEntities> GetAll()
{
    var resultado = _repositorioSistema.GetAll();
    return resultado;
}

Data.Repositories class

public IList<TEntities> GetAll()
{
     return _context.Set<TEntities>().ToList();
}

I can not pass the Entity data to the ViewModel in any way.

    
asked by anonymous 21.08.2017 / 00:03

1 answer

2

You need to map the model to the viewModel. there are some libraries for this, among them AutoMapper, which can be downloaded via NuGet.

After downloading you add a class in App_Start, as below:

public static class AutoMapperConfig
{
    public static void Configurar()
    {
        Mapper.Initialize(config =>
        {
            config.AddProfile(new ViewModelToDomainProfile());
            config.AddProfile(new DomainToViewModelProfile());
        });
    }
}

After this I create the DomainToViewModelProfile and ViewModelToDomainProfile classes, I usually create an "AutoMapper" folder in the MVC project and put those two classes inside. In it you will add the mappings, in the class ViewModelToDomainProfile will be the mappings that will pass the viewModel to a model (insert and update) and in the other class, model to viewModel (selects)

public class DomainToViewModelProfile : Profile
{
    public DomainToViewModelProfile()
    {
        CreateMap<SistemaEntities, SistemaViewModel>();
    }
}

public class ViewModelToDomainProfile : Profile
{
    public ViewModelToDomainProfile()
    {
        CreateMap<SistemaViewModel, SistemaEntities>();
    }
}

After this, in Global.asax just call the

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        AutoMapperConfig.Configurar(); //Chamando configuração AutoMapper
    }

Finally, every time you move from a model to a viewModel or a viewModel to a model you need to call the mapping, which in your case would look like this:

public ActionResult Index()
    {
        List<SistemaEntities> resultado = _SistemaDominio.GetAll();
        List<SistemaViewModel> viewModels = Mapper.Map<List<SistemaViewModel>>(resultado);
        return View(viewModels);                 
    }

When creating the mappings (CreateMap) they will serve both collections and simple objects.

    
21.08.2017 / 01:10