【问题标题】:Map a list of objects manually using automapper使用自动映射器手动映射对象列表
【发布时间】:2020-10-30 23:40:41
【问题描述】:

我正在使用自动映射器将一个复杂对象映射到另一个复杂对象,其中源对象有一个对象列表,其属性与目标中的对象列表不匹配。

所以,我正在使用 Linq 手动浏览源中的列表并将其映射到目标对象。

问题是,目标对象是一个数据库对象:

源对象:

public class AutomationDetailsResponse
    {        
        public Guid ServiceId { get; set; }    
        
        public int EngagementId { get; set; } 
        
        public string ServiceRequestName { get; set; }      
        
        public Guid ServiceRequestGUID { get; set; }    
        
        public string OfficeId { get; set; }
        
        public string CountryId { get; set; }  
        
        public string EngagementCode { get; set; }  
        
        public string CanvasDocumentUri { get; set; }  
        
        public string CanvasAudienceUri { get; set; }     

        public List<RequestFile> InputRequestFiles { get; set; }  
        
        public List<RequestFile> OutputRequestFiles { get; set; }  
        
        public string Status { get; set; }       

        public string RequestInitiatedByName { get; set; }    
        
        public string RequestInitiatedBy { get; set; }   
        
        public int DataCenterId { get; set; }   
        
        public DateTime CreatedAt { get; set; }  
        
        public DateTime LastUpdatedAt { get; set; }       

        public List<ActivityFeed> ActivityFeeds { get; set; }   
        
        public List<Guid> TaskIds { get; set; }

        [JsonProperty("Id")]
        public int CanvasRequestId { get; set; }
    }

    public class RequestFile
    {       
        public Guid Id { get; set; }       
        public int FileSequence { get; set; }       
        public Guid GroupId { get; set; }       
        public string GroupName { get; set; }       
        public string FileType { get; set; }       
        public string FileName { get; set; }       
        public int FileSize { get; set; }        
        public Guid DocumentId { get; set; }

        public DateTime CreatedAt { get; set; }
    }

    public class ActivityFeed
    {       
        public int CreatedById { get; set; }       
        public DateTime CreatedAt { get; set; }      
        public string Description { get; set; }       
        public int ActivityType { get; set; }       
        public string UserName { get; set; }        
        public int Id { get; set; }
    }

目标对象:

[Table(nameof(AutomationRequest), Schema = Schemas.SAH)]
    public class AutomationRequest : EntityBase, ICreatedDate, IModifiedDate
    {
        [Required]
        public int CanvasEnvironmentId { get; set; }

        [Required]
        public Guid AppInstanceId { get; set; }

        public Guid CanvasRequestGUID { get; set; }

        public int CanvasRequestId { get; set; }      
        
        public int DownstreamStatusId { get; set; }

        [Required]
        public int CanvasStatusId { get; set; }

        [Required]
        public Guid ServiceCatalogId { get; set; }

        [Required]
        public string RequestName { get; set; }

        [Required]
        [MaxLength(255)]
        public string EngagementId { get; set; }        

        [Required]
        public int CountryId { get; set; }

        [Required]
        public int DataCenterId { get; set; }

        public bool IsDeletedFromSAH { get; set; }

        public bool IsDeletedFromCAH { get; set; }

        [MaxLength(500)]
        public string CreatedByEmail { get; set; }

        [MaxLength(500)]
        public string CreatedByName { get; set; }

        [Required]
        public DateTime CreatedDate { get; set; }

        [MaxLength(38)]
        public string ModifiedBy { get; set; }

        [MaxLength(50)]
        public string OriginatedFrom { get; set; }

        [Required]
        public DateTime ModifiedDate { get; set; }

        public string NavigationUrl { get; set; }

        public int? Version { get; set; }

        [ForeignKey(nameof(CanvasEnvironmentId))]
        public virtual Environment CanvasEnvironment { get; set; }

        [ForeignKey(nameof(CountryId))]
        public virtual Country Country { get; set; }

        [ForeignKey(nameof(ServiceCatalogId))]
        public virtual ServiceCatalog ServiceCatalog { get; set; }

        [ForeignKey(nameof(CanvasStatusId))]
        public virtual AutomationRequestStatus CanvasStatus { get; set; }        

        public virtual ICollection<AutomationRequestInputFile> InputFiles { get; set; }

        public virtual ICollection<AutomationRequestOutputFile> OutputFiles { get; set; }

        public virtual ICollection<AutomationRequestTask> Tasks { get; set; }
    }
[Table(nameof(AutomationRequestInputFile), Schema = Schemas.SAH)]
    public class AutomationRequestInputFile : EntityBase, ICreatedDate, IModifiedDate
    { 
        [Required]
        public Guid CanvasGroupId { get; set; }
        
        public Guid CanvasDocumentId { get; set; }

        [MaxLength(255)]
        public string FileName { get; set; }

        [MaxLength(38)]
        public string CreatedBy { get; set; }

        [Required]
        public DateTime CreatedDate { get; set; }

        [MaxLength(38)]
        public string ModifiedBy { get; set; }

        [Required]
        public DateTime ModifiedDate { get; set; }

        [Required]        
        public Guid AutomationRequestId { get; set; }      
        
        public string FileType { get; set; }

        [ForeignKey(nameof(AutomationRequestId))]
        public virtual AutomationRequest AutomationRequest { get; set; }

       
    }
 public class EntityBase
    {
        public EntityBase()
        {
            Id = Guid.NewGuid();
        }

        public Guid Id { get; set; }
    }

这是映射配置:

CreateMap<AutomationDetailsResponse, AutomationRequest>()
                .ForMember(dst => dst.Id, opt => opt.Ignore())
                .ForMember(
                    dst => dst.CanvasRequestGUID,
                    opt => opt.MapFrom(src => src.ServiceRequestGUID))
                .ForMember(
                    dst => dst.RequestName,
                    opt => opt.MapFrom(src => src.ServiceRequestName))
                .ForMember(
                    dst => dst.InputFiles,
                    opt => opt.MapFrom(src => src.InputRequestFiles.Select(x => new AutomationRequestInputFile { CanvasGroupId = x.GroupId, CanvasDocumentId = x.DocumentId, FileName = x.FileName, FileType = x.FileType })))
                .ForMember(
                    dst => dst.OutputFiles,
                    opt => opt.MapFrom(src => src.OutputRequestFiles.Select(x => new AutomationRequestOutputFile { CanvasDocumentId = x.DocumentId,FileName = x.FileName, FileType = x.FileType, FileSize = x.FileSize, CreatedDate = x.CreatedAt })))
                .ForMember(
                    dst => dst.CreatedByName,
                    opt => opt.MapFrom(src => src.RequestInitiatedByName))
                 .ForMember(
                    dst => dst.CreatedDate,
                    opt => opt.MapFrom(src => src.CreatedAt))
                 .ForMember(
                    dst => dst.ModifiedDate,
                    opt => opt.MapFrom(src => src.LastUpdatedAt))
                 .ForMember(
                    dst => dst.Tasks,
                    opt => opt.MapFrom(src => src.TaskIds.Select(x => new AutomationRequestTask { CanvasId = x })))
                ;

映射有效。问题是这样的:

var automation = await _dbContext.AutomationRequests.FirstOrDefaultAsync(x => x.CanvasRequestGUID == automationDetails.ServiceRequestGUID);
 _mapper.Map(automationDetails, automation);
 _dbContext.Update(automation);
 await _dbContext.SaveChangesAsync();

更新失败是因为,在映射配置中,我们创建了一个新的实例 AutomationRequestInputFile,它触发了 EntityBase 中的构造函数,创建了一个新的 Id。当 EF Core 尝试更新行时,由于 Id 已更改,它找不到记录。

我已经尝试解决这个问题 1 天了,但没有取得任何进展。

感谢任何帮助。

谢谢。

【问题讨论】:

  • 能否分享一下错误信息?
  • 数据库操作预计会影响 1 行,但实际上会影响 0 行。这是错误,因为自动映射器更改了 AutomationRequestInputFile 的 Id,当我尝试更新时,更新失败,因为 EF Core 无法在 db 中找到记录,因为 id 错误。
  • 您需要使用此代码解决什么业务需求?从数据库中提取记录,然后将其映射到另一个对象并更新该记录,这听起来与直觉相反。 90% 的情况下,您从数据库中提取一条记录,对其进行一些更改,然后将其直接发送回数据库。为什么要将它映射到另一个对象。
  • 存在业务需求。
  • 你试过_dbContext.AutomationRequests.Update(automation)而不是_dbContext.Update(automation);

标签: c# asp.net-core .net-core entity-framework-core automapper


【解决方案1】:

您没有正确使用 AutoMapper,因为您仍在手动构造 AutomationRequestInputFile 对象(通过使用 LINQ .Select())。

解决方案是为RequestFile 添加第二个映射到AutomationRequestInputFile 并删除'InputFiles' 属性的MapFrom 配置中的Select。

这是一个有效的 .NET Fiddle(您的问题中未提供的属性和类型已被省略):https://dotnetfiddle.net/9qizfk

【讨论】:

  • 我认为这会解决它。我完全按照你的建议做了,但是在映射之后仍然为每个 inputrequestfile 创建一个新的 id,并且数据库更新仍然失败。我什至为这张地图添加了:.ForMember(dst =&gt; dst.Id, opt =&gt; opt.Ignore()) :CreateMap()
猜你喜欢
  • 2021-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-02
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
相关资源
最近更新 更多