1

I use MVC in Asp.net using AutoMapper.

As you can see from this code

 Event eventObj = Mapper.Map<EventEditViewModel, Event>(eventEditViewModel);

I'm trying to convert map EventEditViewModel to Event.

I would need need to use my Service layer to convert the CandidateId to an actual Entity.

Any idea if it is possible to do this in AutoMapper? how to setup it

public class Event() { public Class Candidate {get; set;} }

public class EventEditViewModel()
{
    public string CandidateId {get; set;}
}
GibboK
  • 71,848
  • 143
  • 435
  • 658

3 Answers3

3

You should avoid using AutoMapper to retrieve entities from a service layer. Ideally it should be used to map directly between the properties of the given types.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I agree in general, but, why not? It doesn't "feel right", but sometimes you need to go from DTO to entity, and so you need to load something from the database. Is there maybe a better way? [I asked something similar here](https://stackoverflow.com/questions/39189241/using-automapper-to-load-entities-from-the-database). – h bob Aug 28 '16 at 08:11
1

I think you need to create a map first as in:

Mapper.CreateMap<EventEditViewModel, Event>();

before you use it.

Betty
  • 9,109
  • 2
  • 34
  • 48
Peter Smith
  • 5,528
  • 8
  • 51
  • 77
1

Sometimes this can be useful, however I try to only use Automapper in my service layer (aka all inputs and outputs to the service are special input and output models):

Mapper.CreateMap<int, Entity>().ConvertUsing( new RepoTypeConverter<Entity>() );

public class NullableRepoTypeConverter<T> : ITypeConverter<int, T>
{
    public T Convert( ResolutionContext context )
    {
        int? src = (int?)context.SourceValue;
        if (src != null && src.HasValue) {
            return Repository.Load<T>( src.Value );
        } else {
            return default(T);
        }
    }

    // Get Repository somehow (like injection)
    private IRepository repository;
    public IRepository Repository
    {
        get
        {
            if (repository == null) {
                repository = KernelContainer.Kernel.Get<IRepository>();
            }
            return repository;
        }
    }
}
Daniel Little
  • 16,975
  • 12
  • 69
  • 93