如何在 .net 核心中使用自动映射器在目标中保留值

How to preserve values in destination using auto mapper in .net core

我们在 .net 核心中使用 AutoMapper (9.0.0) 来映射源和目标之间的值。直到时间这工作正常。但是,我们需要在映射后保留目标中的一些值。

我们已尝试对成员使用 UseDestinationValue()Ignore() 方法,但它没有保留现有值。下面是相同的代码。

请求模型

public class RequestModel
{
    public int Id { get; set; }
    public int SubmittedById { get; set; }
    public string Description { get; set; }
    public string Location { get; set; }
}

RequestDto

public class RequestDto
{
    public int Id { get; set; }
    public int SubmittedById { get; set; }
    public string Description { get; set; }
    public string Location { get; set; }
    public string SubmittedByName { get; set; }
}

我们接受 API 中的 Dto 作为请求参数 API

[HttpPost]
        public IActionResult Save([FromBody] RequestDto requestDto)
        {
           // Some logic to save records
        }

因此,在保存记录之前,我们将 RequestDto 映射到 RequestModel 并将该模型传递到 DAL 层以像这样保存记录

var requestModel = MapperManager.Mapper.Map<RequestDto, RequestModel>(RequestDto);

并调用数据层

var requestModel = DAL.Save(RequestModel)

因此,在收到更新的请求模型后,我们再次将其映射到 requestDto,在这种情况下,我们丢失了 SubmittedByName 属性 的值。

return MapperManager.Mapper.Map<RequestModel, RequestDto>(requestModel);

映射器Class

public class RequestProfile: Profile
{
     public RequestProfile()
       {
           CreateMap<RequestModel, RequestDto>()
           CreateMap<RequestDto, RequestModel>()
       }
}

请求中不存在此 SubmittedByName 列 table,但我们希望在保存记录后利用它的值。

那么,我们如何在映射后保留目标值。

感谢任何帮助!

We have tried to used UseDestinationValue() and Ignore() methods on member, but it is not preserving the existing values. Below is the code for the same.

因为那对你不起作用

我建议像这样创建一个通用的 class(假设您有多个 class 的 RequestDto)

class RequesterInfo<T>
{
    public string RequesterName { get; set; } // props you want to preserve
    public T RequestDto { get; set; } // props to be mapped 
}

通过保持映射不变, 并将您的代码修改为如下内容:

var requestModel = MapperManager.Mapper.Map<RequestDto, RequestModel>(RequesterInfo.RequestDto);

所以发生的情况是您修改了对象的 T RequestDto 部分而不修改其他属性。

我认为您必须使用接受目的地的 Map 重载。

这对我有用,在控制台应用程序中使用与您发布的相同模型/dto:

    var config = new MapperConfiguration(cfg => cfg.CreateMap<RequestModel, RequestDto>().ReverseMap());
    var mapper = config.CreateMapper();

    var source = new RequestDto
    {
        Id = 1,
        SubmittedById = 100,
        SubmittedByName = "User 100",
        Description = "Item 1",
        Location = "Location 1"
    };

    Console.WriteLine($"Name (original): {source.SubmittedByName}");
    var destination = mapper.Map<RequestDto, RequestModel>(source);
    Console.WriteLine($"Name (intermediate): {source.SubmittedByName}");
    source = mapper.Map<RequestModel, RequestDto>(destination, source);
    Console.WriteLine($"Name (final): {source.SubmittedByName}");

标准 Map 方法创建一个新对象,但重载方法使用现有对象作为目标。