鑑於以下類和解析器,爲什麼會出現此錯誤?我不明白爲什麼要傳入ProductAddModel。AutoMapper解析器未通過預期類型
AutoMapper.AutoMapperMappingException是由用戶代碼
消息=供給值是System.Decimal類型的未處理的但預期 AuctionCMS.Framework.Models.Admin.ProductAddModel。更改值解析器源類型的值 ,或使用FromMember將提供給值解析器的源值重定向到 。
類型:
public class Currency
{
public Int64 Value { get; set; }
// Spot saved for currency type and any other extra properties
}
public class Product
{
public Currency Price { get; set; }
public Currency ReservePrice { get; set; }
}
public class ProductAddModel
{
public Decimal Price { get; set; }
public Decimal ReservePrice { get; set; }
}
解析器代碼:
public class DecimalToCurrencyValueResolver : ValueResolver<decimal, Currency>
{
#region Overrides of ValueResolver<decimal,Currency>
protected override Currency ResolveCore(decimal source)
{
return new Currency() { Value = (Int64)((decimal)source) * 1000 };
}
#endregion
}
public class CurrencyToDecimalValueResolver : ValueResolver<Currency, decimal>
{
#region Overrides of ValueResolver<decimal,Currency>
protected override decimal ResolveCore(Currency source)
{
return (decimal)source.Value * 1000;
}
映射代碼:
Mapper.CreateMap<ProductAddModel, Product>()
.ForMember(x => x.Price, opt => opt.ResolveUsing<DecimalToCurrencyValueResolver>())
.ForMember(x => x.ReservePrice, opt => opt.ResolveUsing<DecimalToCurrencyValueResolver>());
Mapper.CreateMap<Product, ProductAddModel>()
.ForMember(x => x.Price, opt => opt.ResolveUsing<CurrencyToDecimalValueResolver>())
.ForMember(x => x.ReservePrice, opt => opt.ResolveUsing<CurrencyToDecimalValueResolver>());
var model = new ProductAddModel();
var product = new Product();
Mapper.Map<ProductAddModel, Product>(model, product);
什麼我做錯了,是這樣的方法來處理簡單的最佳方式在映射過程中轉換?
謝謝!
我幾乎得出了相同的結論。謝謝! – rboarman
完美!完全是我需要解決我的問題的提示。 –