我试图将一个简单的模型映射到一个实体,但得到了一个我没有预料到的未映射项目的列表,它在 AutomapperCfg 的验证行失败了:
SaveImportRunDetailsModel -> ImportRunDetailEntity (Destination member list) FCSD.Models.SaveImportRunDetailsModel -> LLBLGEN.EntityClasses.ImportRunDetailEntity (Destination member list)
未映射的属性:
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 中取出“自动”,因此您可能需要考虑这样的事情 AutoMapper: "Ignore the rest"? - 这将自动忽略源对象上不存在的所有目标成员。
还有一件事
您可能想要编写一个配置 Mapper
的单元测试使用所有映射实例,然后调用 Mapper.AssertConfigurationIsValid()
在测试时而不是在运行时发现任何问题,因为默认情况下,AutoMapper 在您第一次尝试使用它之前不会费心验证映射。
关于c# - automapper 意外字段 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31918475/