1

我在 .Net Core 3 应用程序中使用 Automapper,我有一个非常简单的场景,我没有意识到我做错了什么。

目标对象未保留未使用字段中的值。

按照下面我正在使用的代码....

  1. 源类

    public class Origin
    {
    
        public long key { get; set; }
        public List<OriginItem> items { get; set; } = new List<OriginItem>();
    
    } //class
    
    public class OriginItem 
    {
        public string itemFieldA { get; set; }
        public string itemFieldB { get; set; }
    } //class
    
  2. 目的地等级

    public class Destination
    {
    
        public long key { get; set; }
        public List<DestinationItem> items { get; set; } = new List<DestinationItem>();
    
    } //class
    
    public class DestinationItem 
    {
        public string itemFieldA { get; set; }
        public string itemFieldB { get; set; }
        public string itemFieldC { get; set; }  //I want to preserve this information      
        public string itemFieldD { get; set; }  //I want to preserve this information
    } //class
    

我对此类的 Automapper 配置文件是:

public class ProfileAutoMapping : Profile
{

    public ProfileAutoMapping ()
    {
        CreateMap<Origin, Destination>();
    } //constructor

} //class

public class ItemAutoMapping : Profile
{

    public ItemAutoMapping ()
    {
        CreateMap<OriginItem, DestinationItem>()
          .ForMember(dest => dest.itemFieldC, opt => opt.UseDestinationValue())
          .ForMember(dest => dest.itemFieldD, opt => opt.UseDestinationValue())
    } //constructor

} //class

我在以下操作中使用地图

    public IActionResult action(Origin origin)
    {

        Destination destination = _repository.GetById(origin.key);

        if (destination!= null)
        {
            _mapper.Map(origin, destination);

            //Updating 
            _repository.Update(destination);

        } //if

        return View();

    } //action

问题:应用 Map 后,destinaton 对象未将原始值保留在未使用的字段中

映射前的Origin对象(JSON格式仅供理解):

  "origin" : { 
    "key": "1", 
     "items" : [
       {"itemFieldA": "X",
        "itemFieldB": "Y" 
       }]
   }

  "destination" : { 
    "key": "1", 
     "items" : [
       {"itemFieldA": "A",
        "itemFieldB": "B", 
        "itemFieldC": "C", 
        "itemFieldD": "D", 
       }]
   }

应用 Map() 后

  "destination" : { 
    "key": "1", 
     "items" : [
       {"itemFieldA": "X",
        "itemFieldB": "Y", 
        "itemFieldC": null, //<============= **ERROR! I want to maintain the original value**
        "itemFieldD": null //<============= **ERROR! I want to maintain the original value**
       }]
   }
4

0 回答 0