如何使用Automapper映射这两个类

时间:2016-02-18 04:27:13

标签: .net c#-4.0 entity-framework-6 asp.net-web-api2 automapper

我有这两个类,我试图将DropOffLocationRequest映射到Package类,但是它无法映射DropOffGeoLocation,我也使用了ResolveCore但是给了我错误

  

缺少类型地图配置或不支持的映射

如果我要求automapper在映射时忽略Package类的DropOffGeoLocation,那么没有错误并且工作正常。

  

映射代码

public void Configure()
        {
            Mapper.CreateMap<DropOffLocationRequest, Package>()
                .ForMember(des => des.DropOffGeoLocation., opt => opt.ResolveUsing<DropOffGeoLocationResolver>())
                .ForMember(des => des.Name, src => src.Ignore())
                .ForMember(des => des.IdNo, src => src.Ignore())
                .ForMember(des => des.IsEnabled, src => src.Ignore())
                .ForMember(des => des.Comments, src => src.Ignore())
                .ForMember(des => des.RowCreateDate, src => src.Ignore())
                .ForMember(des => des.RowUpdateDate, src => src.Ignore()));
        }
public class DropOffLocationRequest
    {
        public string Id { get; set; }
        public double Longitude { get; set; }
        public double Latitude { get; set; }
        public string Comments { get; set; }
        public ActionType ActedBy { get; set; }
        public DevicePlatform Device { get; set; }
        public DateTimeOffset DeviceDateTimeOffSet { get; set; }
    }
public partial class Package
    {       

        public string Name { get; set; }
        public string IdNo { get; set; }
        public bool IsEnabled { get; set; }
        public System.Data.Entity.Spatial.DbGeography DropOffGeoLocation { get; set; }
        public string Comments { get; set; }
        public Nullable<System.DateTimeOffset> RowCreateDate { get; set; }
        public Nullable<System.DateTimeOffset> RowUpdateDate { get; set; }
    }
  

ResolveCore class

public class DropOffGeoLocationResolver : ValueResolver<DropOffLocationRequest, Package>
    {
        protected override Package ResolveCore(DropOffLocationRequest source)
        {
            var point = string.Format("POINT({1} {0})", source.Latitude, source.Longitude);
            return new Package { DropOffGeoLocation = DbGeography.FromText(point) };
        }

    }

不知道我搞砸了什么。

由于

1 个答案:

答案 0 :(得分:0)

问题在于您的值解析程序正在创建整个Package,但它应该只是创建DbGeography(因为您使用值解析程序仅映射DropOffLocation属性)。

请改为尝试:

public class DropOffGeoLocationResolver :
    ValueResolver<DropOffLocationRequest, DbGeography>
{
    protected override DbGeography ResolveCore(DropOffLocationRequest source)
    {
        var point = string.Format("POINT({1} {0})", source.Latitude, source.Longitude);
        return DbGeography.FromText(point);
    }
}