【问题标题】:Auto mapper issue with Object reference not set to an instance of an object对象引用未设置为对象实例的自动映射器问题
【发布时间】:2022-01-16 17:28:24
【问题描述】:

大家好,在我的情况下,我的自动映射对象确实存在问题,我需要跳过属性并将数据库上下文属性与我的自定义对象映射

这是我尝试转换对象的方式,但出现错误 System.NullReferenceException: '对象引用未设置为对象的实例

var library = await Task.FromResult(mapper.Map<test.WebApi.Dto.Library>(item));

这是我的自定义映射器类

  public class CustomMapper: Profile
  {
    public CustomMapper()
    {
        
        CreateMap<test.WebApi.Models.Library, test.WebApi.Dto.Library>().ForMember(dest => dest.Id, opt => opt.Ignore());
    }
  }

这是我的 dto 类和 dbcontext 类

using System;
using System.Collections.Generic;

#nullable disable

namespace test.WebApi.Models
{
    public partial class Library
    {
        public Library()
        {
            GeneratedFiles = new HashSet<GeneratedFile>();
            Templates = new HashSet<Template>();
        }

        public int Id { get; set; }
        public long? TenantId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public virtual ICollection<GeneratedFile> GeneratedFiles { get; set; }
        public virtual ICollection<Template> Templates { get; set; }
    }
}


using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace test.WebApi.Dto
{
    public class Library
    {
        public int Id { get; set; }
        public long TenantId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }        
    }
}

包裹和信息

AutoMapper 10.1.1 AutoMapper.Extensions.Microsoft.DependencyInjection 8.1.1

.net 核心 5.0

【问题讨论】:

  • 那么,TenantId 如果为空,应该映射成什么?
  • 1. dto 是哪个库? 2. 请与命名空间共享库模型。 3.item怎么获得? 4.你的asp.net core和automapper nuget包是什么版本的?
  • 我已经更新了命名空间和包的详细信息
  • 嗨@Thili,你能分享一下你是如何 DI 映射器的吗,我尝试将 item 设置为 null,但它仍然有效。但是当我以错误的方式 DI 映射器时,就会出现错误。

标签: c# asp.net-core automapper


【解决方案1】:

这是一个完整的工作演示:

public class HomeController : Controller
{
    private readonly IMapper mapper;
    public HomeController(IMapper mapper)
    {
        this.mapper = mapper;
    }
    public void Index()
    {
        var item = new test.WebApi.Models.Library()
        {
            Description = "aa"
        };
        var library = await Task.FromResult(mapper.Map<test.WebApi.Dto.Library>(item));
    }   
}

Startup.cs:

services.AddAutoMapper(typeof(CustomMapper));

【讨论】:

    猜你喜欢
    • 2021-04-09
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多