How to retrieve an Entity when using AutoMapper

207 Views Asked by At

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;}
}
3

There are 3 best solutions below

0
On BEST ANSWER

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;
        }
    }
}
1
On

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

Mapper.CreateMap<EventEditViewModel, Event>();

before you use it.

1
On

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.