可空双精度与整型之间的转换失败



我有一个模型,FittingProject,我试图映射到另一个模型,FittingsProjectSharepointModel

不幸的是,FittingProjectFittingsProjectSharepointModel只共享值,属性名称和类型都不同。

为了简化映射过程,我为FittingProject创建了一个自定义属性,用于查找FittingsProjectSharepointModel上的匹配属性。问题是大多数值在转换过程中失败,例如从intdouble?

从下面的代码片段可以看到,我尝试使用Convert.ChangeType,但它仍然失败,出现了相同的Exception。

public ModelMapper MapModelToFittingsProjectSharepointModel(object model)
{
    if (model == null)
    {
        return null;
    }
    var propertiesWithCustomAttributes = model
        .GetType()
        .GetProperties()
        .Where(p => p.GetCustomAttributes(typeof(SharepointModelPropertyAttribute), true).Length > 0);
    foreach (var prop in propertiesWithCustomAttributes)
    {
        foreach (var customAttribute in prop.GetCustomAttributes(true))
        {
            SharepointModelPropertyAttribute sharePointModelPropertyAttribute = 
                customAttribute as SharepointModelPropertyAttribute;
            PropertyDescriptor sharePointModelprop = TypeDescriptor
                .GetProperties(typeof(FittingsProjectSharepointModel))
                .Find(sharePointModelPropertyAttribute.SharepointModelProperty, false);
            try
            {
                var projectValue = prop.GetValue(model);
                var projectValueConverted = Convert.ChangeType(projectValue, sharePointModelprop.PropertyType);
                sharePointModelprop.SetValue(FittingsProjectSharepointModel, projectValueConverted);
            }
            catch (Exception ex)
            {
                // 
            }
        }
    }
    return this;
}

ChangeType不支持:

Convert.ChangeType(1234, typeof(double)) //works
Convert.ChangeType(1234, typeof(double?)) //fails

所以你可能需要做你自己的可空处理。只需使用Nullable.GetUnderlyingType从目标类型中去掉空属性即可。您还需要处理要转换的值为null的情况。

你可以使用AutoMapper。这样的:

考虑以下示例模型:

public class FittingProject
{
    public string Name { get; set; }
    public int Size { get; set; }
}
public class FittingsProjectSharepointModel
{
    public string Display { get; set; }
    public double? Volume { get; set; }
}

现在,您可以像这样创建模型之间的映射:

AutoMapper.Mapper.CreateMap<FittingProject, FittingsProjectSharepointModel>()
    .ForMember(dest => dest.Display, opts => opts.MapFrom(src => src.Name)) //Map Name to Display
    .ForMember(dest => dest.Volume, opts => opts.MapFrom(src => src.Size)); //Map Size to Volume

下面是如何转换的:

FittingProject fitting_project = new FittingProject()
{
    Name ="project_name",
    Size = 16
};
FittingsProjectSharepointModel sharepoint_model =
    AutoMapper.Mapper.Map<FittingsProjectSharepointModel>(fitting_project);

相关内容

  • 没有找到相关文章

最新更新