在没有映射错误的情况下使用 Automapper `Missing type map configuration or unsupported mapping`

Using Automapper without mapping error `Missing type map configuration or unsupported mapping`

我在我的 .net core 3.1 项目中使用 AutoMapper.Extensions.Microsoft.DependencyInjection Nuget 包。我的控制台应用程序代码如下(可以通过复制粘贴 运行 并安装 AutoMapper.Extensions.Microsoft.DependencyInjection 包来重现错误 )。

我没有写任何映射。我仅将 Automapper 用于克隆对象,如下面的代码所示。 当我使用 6.1.0 包时一切正常。但是当我升级 6.1.1 或 7.0.0 时它给了我错误

Missing type map configuration or unsupported mapping. Mapping types: Foo -> FooDto AutomapperProject.Foo -> AutomapperProject.FooDto

这可能是什么原因?

using AutoMapper;

namespace AutomapperProject
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var foo = new Foo { Id = 1, Name = "Foo" };
            var dto = MapperHelper.MapFrom<FooDto>(foo);
        }
    }

    public static class AutomapperExtensions
    {
        private static void IgnoreUnmappedProperties(TypeMap map, IMappingExpression expr)
        {
            foreach (string propName in map.GetUnmappedPropertyNames())
            {
                var srcPropInfo = map.SourceType.GetProperty(propName);

                if (srcPropInfo != null)
                    expr.ForSourceMember(propName, opt => opt.DoNotValidate());

                var destPropInfo = map.DestinationType.GetProperty(propName);

                if (destPropInfo != null)
                    expr.ForMember(propName, opt => opt.Ignore());
            }
        }

        public static void IgnoreUnmapped(this IProfileExpression profile)
        {
            profile.ForAllMaps(IgnoreUnmappedProperties);
        }
    }

    public static class MapperHelper
    {
      private static IMapper Mapper()
      {
        var mapperConfig = new MapperConfiguration(configuration=>{configuration.IgnoreUnmapped();});    
        return mapperConfig.CreateMapper();
      }

      public static T MapFrom<T>(object entity)
      {
          return Mapper().Map<T>(entity);
      }
    }

    public class Foo
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class FooDto
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Unmapped { get; set; }
    }
}

7.0.0 版中的 AutoMapper.Extensions.Microsoft.DependencyInjection 包需要(至少)9.0.0 版中的 AutoMapper 包。 6.1.0 版中的 AutoMapper.Extensions.Microsoft.DependencyInjection 包需要(至少)8.1.0 版中的 AutoMapper 包。

AutoMapper 从 8.0 到 9.0 的变化有一个重要的变化,它会影响您的代码,如 9.0 Upgrade Guide:

中所写

AutoMapper no longer creates maps automatically (CreateMissingTypeMaps and conventions)

You will need to explicitly configure maps, manually or using reflection. Also consider attribute mapping.

因此,对于新的 AutoMapper 9.0.0,您必须明确定义映射。

如果您使用 Automapper 包 9.0.0 或更高版本,您将需要明确配置地图。正如@Progman 所说。

我解决了将 AutoMapper 降级到 8.0.0 和 AutoMapper.Extensions.Microsoft.DependencyInjection 到版本 6.0.0