Reputation: 8681
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
Reputation: 1504
You've missed posting some code:
AutoMapper.Initialize
setupIf 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.
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