Automapper 无法将类型 'Parent' 的对象转换为类型 'Child'

Automapper Unable to cast object of type 'Parent' to type 'Child'

我有两个 classes Base short class

 public class ObjectShortEditView
 {
        public string FirstName { get; set; }
        public string LastName { get; set; }
 }

完整视图

public class ObjectEditView : ObjectShortEditView
 {
        public string Phone { get; set; }
}

在自动映射器配置文件中

Mapper.CreateMap<Entity, ObjectShortEditView>().IgnoreAllNonExisting();
Mapper.CreateMap<Entity, ObjectEditView >().IgnoreAllNonExisting();

IgnoreAllNonExistingExtension

public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>
            (this IMappingExpression<TSource, TDestination> expression)
        {
            var flags = BindingFlags.Public | BindingFlags.Instance;
            var sourceType = typeof(TSource);
            var destinationProperties = typeof(TDestination).GetProperties(flags);

            foreach (var property in destinationProperties)
            {
                if (sourceType.GetProperty(property.Name, flags) == null)
                {
                    expression.ForMember(property.Name, opt => opt.Ignore());
                }
            }
            return expression;
        }

问题是当我尝试从实体映射到完整编辑视图时失败了

var view = Mapper.Map<ObjectEditView>(entityFromDb);

有时它会因异常而失败

Unable to cast object of type 'ObjectShortEditView' to type 'ObjectEditView '.

意思是当我写这篇文章时我知道它可以忽略所有扩展但是为什么当我要求将我映射到完整视图时它甚至试图投射到短视图...

我没有尝试你的方案,但是有一个 .Include<> 语法可以帮助处理继承主题。您可以这样声明:

Mapper.CreateMap<Entity, ObjectShortEditView>()
    .Include<Entity, ObjectEditView>()
    .IgnoreAllNonExisting();
Mapper.CreateMap<Entity, ObjectEditView>().IgnoreAllNonExisting();

也许这可以解决您的问题。

您使用的是 AutoMapper 版本 4 吗?甚至可以结合 EF 6.x?

看起来这可能与您的主题有关:https://github.com/AutoMapper/AutoMapper/issues/842

那么一个语句是:"Please consider downgrade to AutoMapper 3.3.1"