When I am mapping using mapper between the model the error is being showed AutoMapper.AutoMapperMappingException: 'Error mapping types.'
I have the following model
public class Country { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] [MaxLength(50, ErrorMessage = "Country must be up to 50 characters in length")] public string CountryName { get; set; } public ICollection<Author> Authors { get; set; } } public class CountryDto { public int Id { get; set; } public string CountryName { get; set; } public ICollection<AuthorDto> Authors { get; set; } } public class Author { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] [MaxLength(100, ErrorMessage ="First Name cannot be more than 100 characters")] public string FirstName { get; set; } [Required] [MaxLength(200, ErrorMessage = "Last Name cannot be more than 200 characters")] public string LastName { get; set; } public Country Country { get; set; } [NotMapped] public ICollection<BookAuthor> BookAuthors { get; set; } } public class AuthorDto { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } }
startup.cs public void ConfigureServices(IServiceCollection services) { services.AddDbContext<BookStoreDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddControllers(); services.AddScoped<ICountryRepository, CountryRepository>(); services.AddAutoMapper(typeof(Mapping)); } API Controller public IActionResult GetCountries() { var objList = _countryRepository.GetCountries(); var mappedEntities = _mapper.Map<CountryDto[]>(objList); if (!ModelState.IsValid) return BadRequest(ModelState); return Ok(mappedEntities); }
Repository class
public Country[] GetCountries() { // return _db.Countries.Include(a=> a.Authors).OrderBy(c => c.CountryName).ToList(); IQueryable<Country> query = _db.Countries .Include(a => a.Authors); return query.ToArray(); }
Mapping.cs
public class Mapping : Profile { public Mapping() { CreateMap<Country, CountryDto>() .ReverseMap() .ForMember(a => a.Authors, a => a.Ignore()); } }
When I map the error is coming is as follows
AutoMapper.AutoMapperMappingException: 'Error mapping types.'