Home > OS >  AutoMapper Entity to Dto Conversion: Mapping Type Error
AutoMapper Entity to Dto Conversion: Mapping Type Error

Time:09-26

There are data in my entities that should not be exposed to the outside. So I want to export the entity by mapping it to a dto. The data comes to me of type IList<Article>. I need to convert it to IList<ArticleBasicDto> but when I try to do it I get an error.

I tried to export IList<ArticleBasicDto> as the target in this way, but failed. Since I am just learning, I could not reach the result, what should I do?

The reason I do this is because there is too much information about the User entity in the Article. In addition, there is a Category field in the Article Object in the JSON output, and the articles belonging to the Category are listed again in this field. I am trying to use Dto to get rid of these unnecessary fields.

Error Message

An unhandled exception occurred while processing the request. AutoMapperMappingException: Missing type map configuration or unsupported mapping.

Mapping types: Article -> ArticleBasicDto Blog.Entities.Concrete.Article -> Blog.Entities.Dtos.ArticleBasicDto lambda_method178(Closure , Article , ArticleBasicDto , ResolutionContext )

AutoMapperMappingException: Error mapping types.

Mapping types: IList1 -> IList1 System.Collections.Generic.IList1[[Blog.Entities.Concrete.Article, Blog.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.IList1[[Blog.Entities.Dtos.ArticleBasicDto, Blog.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] lambda_method177(Closure , IList , IList , ResolutionContext )

Mapper Profile

namespace Blog.Business.AutoMapper.Profiles
{
    public class ArticleProfile : Profile
    {
        public ArticleProfile()
        {
           CreateMap<Article, ArticleBasicDto>().ForMember(dest => dest.Category, opt => opt.MapFrom(x => x.Category)).ForMember(dest => dest.User,
                opt => opt.MapFrom(x => x.User));
        }
    }
}

Dtos

namespace Blog.Entities.Dtos
{
    public class ArticleBasicDto
    {
        public string Title { get; set; }
        public string Content { get; set; }
        public string Thumbnail { get; set; }
        public DateTime Date { get; set; }
        public int ViewsCount { get; set; } = 0;
        public int CommentCount { get; set; } = 0;
        public UserBasicDto User { get; set; }
        public CategoryBasicDto Category { get; set; }
    }
}

namespace Blog.Entities.Dtos
{
    public class CategoryBasicDto
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public string Slug { get; set; }
    }
}

namespace Blog.Entities.Dtos
{
    public class UserBasicDto
    {
        public string Email { get; set; }
        public string Username { get; set; }
        public string Picture { get; set; }
    }
}

Manager GetAllBasic Method

public async Task<IDataResult<ArticleBasicListDto>> GetAllBasic()
        {
            var results = await _unitOfWork.Articles.GetAllAsync();
            var mapping = _mapper.Map<IList<ArticleBasicDto>>(results);
            return new DataResult<ArticleBasicListDto>(ResultStatus.Success, new ArticleBasicListDto()
            {
                Articles = mapping,
            });
        }

MVC Layer - Startup.cs

namespace Blog.MVC
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews().AddRazorRuntimeCompilation().AddNewtonsoftJson(opt => opt.SerializerSettings.ReferenceLoopHandling
                = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
            services.AddAutoMapper(typeof(Startup));
            services.LoadMyServices();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseStatusCodePages();
            }

            app.UseStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapAreaControllerRoute(
                    name: "Admin",
                    areaName: "Admin",
                    pattern: "Admin/{controller=Home}/{action=Index}/{id?}"
                );
                endpoints.MapDefaultControllerRoute();
                endpoints.MapControllers();
            });
        }
    }
}

CodePudding user response:

To fix this you have to replace the startup class with the ArticleProfile like below services.AddAutoMapper(typeof(ArticleProfile ));

It will resolve your issue.

CodePudding user response:

you need to define mappings for user and category

CreateMap<User,CategoryBasicDto>();
CreateMap<Category,CategoryBasicDto>();
  • Related