简体   繁体   English

AutoMapper 实体到 Dto 转换:映射类型错误

[英]AutoMapper Entity to Dto Conversion: Mapping Type Error

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.所以我想通过将实体映射到 dto 来导出实体。 The data comes to me of type IList<Article> .我收到的数据类型为IList<Article> I need to convert it to IList<ArticleBasicDto> but when I try to do it I get an error.我需要将其转换为IList<ArticleBasicDto>但是当我尝试这样做时出现错误。

I tried to export IList<ArticleBasicDto> as the target in this way, but failed.我尝试以这种方式将IList<ArticleBasicDto>导出为目标,但失败了。 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.另外在JSON output中的文章Object中有一个Category字段,属于该Category的文章在该字段中重新列出。 I am trying to use Dto to get rid of these unnecessary fields.我正在尝试使用 Dto 来摆脱这些不必要的字段。

Error Message错误信息

An unhandled exception occurred while processing the request.处理请求时发生未处理的异常。 AutoMapperMappingException: Missing type map configuration or unsupported mapping. AutoMapperMappingException:缺少类型 map 配置或不支持的映射。

Mapping types: Article -> ArticleBasicDto Blog.Entities.Concrete.Article -> Blog.Entities.Dtos.ArticleBasicDto lambda_method178(Closure, Article, ArticleBasicDto, ResolutionContext )映射类型:文章 -> ArticleBasicDto Blog.Entities.Concrete.Article -> Blog.Entities.Dtos.ArticleBasicDto lambda_method178(Closure, Article, ArticleBasicDto, ResolutionContext )

AutoMapperMappingException: Error mapping types. AutoMapperMappingException:错误映射类型。

Mapping types: IList 1 -> IList 1 System.Collections.Generic.IList 1[[Blog.Entities.Concrete.Article, Blog.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.IList 1[[Blog.Entities.Dtos.ArticleBasicDto, Blog.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] lambda_method177(Closure, IList, IList, ResolutionContext )映射类型:IList 1 -> IList 1 System.Collections.Generic.IList 1[[Blog.Entities.Concrete.Article, Blog.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.IList 1[[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 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经理GetAllBasic方法

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 MVC 层 - 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();
            });
        }
    }
}

To fix this you have to replace the startup class with the ArticleProfile like below services.AddAutoMapper(typeof(ArticleProfile ));要解决此问题,您必须将startup class 替换为如下所示的ArticleProfile services.AddAutoMapper(typeof(ArticleProfile ));

It will resolve your issue.它将解决您的问题。

you need to define mappings for user and category您需要为用户和类别定义映射

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM