Luk*_*988 3 automapper .net-core
在 AutoMapper 8.0 之前,我使用此代码通过字符串查找属性映射,例如:实体模型具有名为“currency_id”的属性,而 DTO 具有名为“currency”的属性。我在 AutoMapper 中定义了双向映射,并使用此代码查找源/目标属性相关
public static string GetDestinationPropertyFor<TSrc, TDst>(IMapper IMapper, string sourceProperty)
{
var mapper = AutoMapper.IMapper.ConfigurationProvider;
// TSrc = source generic type
// TDst = destination generic type
var map = mapper.FindTypeMapFor<TSrc, TDst>();
var propertyMap = map.GetPropertyMaps()
.FirstOrDefault(pm =>
pm.SourceMember.Name == sourceProperty
);
return propertyMap.DestinationProperty.Name;
}
Run Code Online (Sandbox Code Playgroud)
在 AutoMapper 配置文件中:
this.CreateMap<EntityModels.contact, DTO.contact>()
.ForMember(m => m.currency, src => src.MapFrom(f => f.currency_id))
;
this.CreateMap<DTO.contact, EntityModels.contact>()
.ForMember(m => m.currency_id, src => src.MapFrom(f => f.currency))
;
Run Code Online (Sandbox Code Playgroud)
当我这样调用我的方法时:
var _dboField = GetDestinationPropertyFor<DTO.contact, EntityModels.contact>(this.mapper, "currency");
Console.WriteLine(_dboField);
// output should be "currency_id"
Run Code Online (Sandbox Code Playgroud)
升级到 AutoMapper 8.0 后,我在构建时遇到此错误:
“TypeMap”不包含“GetPropertyMaps”的定义,并且找不到接受“TypeMap”类型的第一个参数的可访问扩展方法“GetPropertyMaps”(您是否缺少 using 指令或程序集引用?)
AutoMapper 8.0 中 GetPropertyMaps 的替代品是什么?
谢谢!
正如 Lucian 所建议的,MemberMaps 是一个可能的替代品。但是,PropertyMaps 与 AutoMapper 7.0 中的 GetPropertyMaps 完全相同。DestinationProperty也已更名为DestinationMember.
AutoMapper 7.0 代码:
public static string GetDestinationPropertyFor<TSrc, TDst>(IMapper IMapper, string sourceProperty)
{
var mapper = AutoMapper.IMapper.ConfigurationProvider;
// TSrc = source generic type
// TDst = destination generic type
var map = mapper.FindTypeMapFor<TSrc, TDst>();
var propertyMap = map.GetPropertyMaps()
.FirstOrDefault(pm =>
pm.SourceMember.Name == sourceProperty
);
return propertyMap.DestinationProperty.Name;
}
Run Code Online (Sandbox Code Playgroud)
AutoMapper 8.0 代码:
public static string GetDestinationPropertyFor<TSrc, TDst>(IMapper IMapper, string sourceProperty)
{
var mapper = AutoMapper.IMapper.ConfigurationProvider;
// TSrc = source generic type
// TDst = destination generic type
var map = mapper.FindTypeMapFor<TSrc, TDst>();
var propertyMap = map.PropertyMaps
.FirstOrDefault(pm =>
pm.SourceMember.Name == sourceProperty
);
return propertyMap.DestinationMember.Name;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2217 次 |
| 最近记录: |