![](/img/trans.png)
[英]c# - AutoMapper: how to copy fields from 2 different sources into 1 destination
[英]automapper unexpected fields c#
我試圖將一個簡單的模型映射到一個實體,但得到一個我沒想到的未映射項目列表,它在AutomapperCfg的驗證行中失敗:
SaveImportRunDetailsModel - > ImportRunDetailEntity(目標成員列表)FCSD.Models.SaveImportRunDetailsModel - > LLBLGEN.EntityClasses.ImportRunDetailEntity(目標成員列表)
未映射的屬性:
Id
ConcurrencyPredicateFactoryToUse
AuthorizerToUse
AuditorToUse
Validator
ActiveContext
IsNew
Fields
IsDirty
這些看起來像系統生成的項目,有沒有辦法解雇它們?
AutomapperCfg.cs是
using AutoMapper;
using FCSD.Models;
using LLBLGEN.EntityClasses;
namespace FCSD.Automapper
{
public class AutomapperCfg : IAutomapperCfg
{
public void Configure()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<CategoryEntity, Category>(MemberList.Destination);
cfg.CreateMap<EnglishPartInfoEntity, EnglishPartModel>(MemberList.Destination);
cfg.CreateMap<ImageEntity, Image>(MemberList.Destination);
cfg.CreateMap<ImportRunDetailEntity, ImportRunDetailModel>(MemberList.Destination);
cfg.CreateMap<ModelExportBaseEntity, Model>(MemberList.Destination).ReverseMap();
cfg.CreateMap<PartEntity, Part>(MemberList.Destination);
cfg.CreateMap<SaveImportRunDetailsModel, ImportRunDetailEntity>(MemberList.Destination);
});
Mapper.AssertConfigurationIsValid();
}
}
}
SaveImportRunDetailsModel是
using System;
namespace FCSD.Models
{
public class SaveImportRunDetailsModel
{
public string PHCreationDate { get; set; }
public DateTime RunTimestamp { get; set; }
}
}
最后,ImportRunDetailEntity有點長(超過400行)並且是從LLBLGen Pro自動生成的c#。
發生了什么
如果目標類型包含與源上的屬性不匹配的任何屬性,如果尚未明確告知如何填充該屬性,AutoMapper將拋出異常。
如何解決它
如果您不希望AutoMapper填充屬性,那么您應該在CreateMap<TSource, TDest>()
的返回上使用此擴展方法,以便忽略每個字段:
.ForMember(dest => dest.Id, opt => opt.Ignore())
.ForMember(dest => dest.ConcurrencyPredicateFactoryToUse, opt => opt.Ignore())
.ForMember(dest => dest.AuthorizerToUse, opt => opt.Ignore());
等等。
但那很糟糕......
顯然這有點拖累並且從AutoMapper中取出“auto”,所以你可能想要考慮像這樣的AutoMapper:“忽略其余的”? - 它將自動忽略源對象上不存在的所有目標成員。
還有一件事
您可能希望編寫一個單元測試,使用所有映射配置Mapper
實例,然后調用Mapper.AssertConfigurationIsValid()
在測試Mapper.AssertConfigurationIsValid()
不是在運行時發現任何問題,因為默認情況下,AutoMapper將不會打擾驗證映射,直到第一次嘗試使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.