为具有自动映射器类型的所有成员配置约定



我所有的域模型都有字段public CurrencyId CurrencyId {get; set;}。我所有的视图模型都已提交public CurrencyVm Currency {get; set;}。自动映射器知道如何Map<CurrencyVm>(CurrencyId)。如何设置自动约定,这样我就不必.ForMember(n => n.Currency, opt => opt.MapFrom(n => n.CurrencyId));

ForAllMaps就是答案,谢谢@LucianBargaoanu。这段代码有点有效,但尚未在所有情况下都经过测试。我也不知道如何检查所选属性之间是否存在映射。

configuration.ForAllMaps((map, expression) =>
{
if (map.IsValid != null)
{
return; // type is already mapped (or not)
}
const string currencySuffix = "Id";
var currencyPropertyNames = map.SourceType
.GetProperties()
.Where(n => n.PropertyType == typeof(CurrencyId) && n.Name.EndsWith(currencySuffix))
.Select(n => n.Name.Substring(0, n.Name.Length - currencySuffix.Length))
.ToArray();
expression.ForAllOtherMembers(n =>
{
if (currencyPropertyNames.Contains(n.DestinationMember.Name, StringComparer.OrdinalIgnoreCase))
{
n.MapFrom(n.DestinationMember.Name + currencySuffix);
}
});
});

最新更新