Search code examples
asp.netasp.net-mvcasp.net-mvc-3automapperautomapper-2

How to retrieve an Entity when using AutoMapper


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

Solution

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