Tom
Tom

Reputation: 8681

How to convert Dto object to entity before passing it to business layer

I have implemented Automapper in business layer in .Net. The methods are async tasks. The method GetAllMovies() compiles where as AddMovie doesn't. I need to convert Dto to entity before passing it to the service method. How would I go about doing it

methods

       public async Task<long> AddMovie(MoviesDto movie)
        {
            return await _movieService.AddMovie(movie);

        }

        public async Task<IEnumerable<MoviesDto>> GetAllMovies()
        {
            var movies = await _movieService.GetMovies();
            return Mapper.Map<List<MoviesDto>>(movies);
        }

Movie Service

public class MovieService : IMovieService
    {
        IUnitOfWork _unitOfWork;
        public MovieService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public async Task<long> AddMovie(Movie movie)
        {
            return await _unitOfWork.movieRepository.AddMovie(movie);
        }


        public async Task<IEnumerable<Movie>> GetMovies()
        {
            return await _unitOfWork.movieRepository.GetMovies();
        }
    }

AutoMapper

public class DomainToDtoMapping : Profile
    {
        public DomainToDtoMapping()
        {
            CreateMap<BaseEntity, BaseDto>().ReverseMap();
            CreateMap<Movie, MoviesDto>().ReverseMap();

        }
    }

StructureMap

public DefaultRegistry()
        {
            Scan(
                scan =>
                {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
                });
            //For<IExample>().Use<Example>();

            For<IConnectionFactory>().Use<ConnectionFactory>();
            //For<IMovieRepository>().Use<MovieRepository>().Ctor<FileInfo>().Is(myFile);
            For<IUnitOfWork>().Use<UnitOfWork>();
            For<IMovieService>().Use<MovieService>();
            For<IMovieBusiness>().Use<MovieBusiness>();
        }

Upvotes: 1

Views: 2271

Answers (1)

woelliJ
woelliJ

Reputation: 1504

You've missed posting some code:

  • what does your MovieService look like?
  • are you using entity framework or something else?
  • your AutoMapper.Initialize setup

If MovieDbo (or whatever your database class is called) doesn't reference any other database objects (via navigation properties) you can call Mapper.Map<MovieDbo>(movie) after you have configured it appropriately.

With your DBO having navigation Properties it is getting complex and a regular object creation with new can safe you from a lot of troubles.


update

Try this. Like i said, there shouldn't be any problem if Movie didn't have any navigation properties. If it does you better just create a new instance and map the properties by hand.

public async Task<long> AddMovie(MoviesDto movie)
{
    return await _movieService.AddMovie(AutoMapper.Map<Movie>(movie));

}

Upvotes: 2

Related Questions