当我尝试在我的应用程序中调用 Mapper.Map 时出现以下异常:
AutoMapper.AutoMapperMappingException.
Mapping types:
Double -> Double
System.Double -> System.Double
Destination path:
Address.Latitude
Source value:
42.250287
System.InvalidCastException. Unable to cast object of type 'Acme.Order' to type 'Acme.Address'.
除了明显的错误表明它无法映射相同类型的对象(以及原始类型),事实是我从不从类型“Acme.Order”映射到类型“Acme.Address”!
这是正在使用的实际调用:
var order = Mapper.Map<IDataRecord, Order>(theDataReader);
我的对象模型如下所示:
public class Order
{
public Address Address { get; set; }
public Int32 Number { get; set; }
public PhoneNumber PhoneNumber { get; set; }
}
public class Address
{
public String City { get; set; }
public Double Latitude { get; set; }
public Double Longitude { get; set; }
public Int32 Number { get; set; }
public String PostalCode { get; set; }
public String State { get; set; }
public String Street { get; set; }
}
public class PhoneNumber
{
public String Extension { get; set; }
public String Number { get; set; }
}
我在我的应用程序中定义了以下配置:
CreateMap<IDataRecord, Address>()
.ForMember(target => target.Latitude, opt => opt.MapFrom(record => GetDoubleFrom(record, "Latitude", 0)))
.ForMember(target => target.Longitude, opt => opt.MapFrom(record => GetDoubleFrom(record, "Longitude", 0)))
;
CreateMap<IDataRecord, PhoneNumber>()
.ForMember(target => target.Extension, opt => opt.MapFrom(record => GetStringFrom(record, "Extension", String.Empty)))
.ForMember(target => target.Number, opt => opt.MapFrom(record => GetStringFrom(record, "PhoneNumber", String.Empty)))
;
CreateMap<IDataRecord, Order>()
.ForMember(target => target.Address, opt => opt.ResolveUsing(record => Mapper.Map<IDataRecord, Address>(record)))
.ForMember(target => target.PhoneNumber, opt => opt.ResolveUsing(record => Mapper.Map<IDataRecord, PhoneNumber>(record)))
;
使用这些辅助方法:
private Double GetDoubleFrom(IDataRecord record, String name, Double defaultValue)
{
return (record.Contains(name) && !record.IsDbNull(name)) ? record.GetDouble(name) : defaultValue;
}
private String GetStringFrom(IDataRecord record, String name, String defaultValue)
{
return (record.Contains(name) && !record.IsDbNull(name)) ? record.GetString(name) : defaultValue;
}
(我在 IDataRecord 上有扩展方法,它们采用字段名称、获取序数并使用标准方法返回值,但为简洁起见不会显示它们。)
这是否能说明导致失败的原因?
(顺便说一句,我正在使用 AutoMapper v2.1.267)