【问题标题】:Random "Missing type map configuration or unsupported mapping." Error in Automapper随机“缺少类型映射配置或不支持的映射”。自动映射器中的错误
【发布时间】:2017-10-29 18:49:00
【问题描述】:

解决办法请见this post

好吧,我终于想通了。这: AppDomain.CurrentDomain.GetAssemblies() 我的一段代码有时没有得到我的映射程序集,所以当它丢失时我得到一个错误。通过强制应用程序查找所有程序集来替换此代码解决了我的问题。

我的实体:

    /// <summary>
    /// Get/Set the name of the Country
    /// </summary>
    public string CountryName { get; set; }

    /// <summary>
    /// Get/Set the international code of the Country
    /// </summary>
    public string CountryCode { get; set; }

    /// <summary>
    /// Get/Set the coordinate of the Country
    /// </summary>
    public Coordinate CountryCoordinate { get; set; }

    /// <summary>
    /// Get/Set the cities of the country
    /// </summary>
    public virtual ICollection<City> Cities
    {
        get
        {
            if (_cities == null)
            {
                _cities = new HashSet<City>();
            }

            return _cities;
        }
        private set
        {
            _cities = new HashSet<City>(value);
        }
    }

我的 DTO:

    public Guid Id { get; set; }

    public string CountryName { get; set; }

    public string CountryCode { get; set; }

    public string Lattitude { get; set; }

    public string Longtitude { get; set; }

    public List<CityDTO> Cities { get; set; }

我的配置

        // Country => CountryDTO
        var countryMappingExpression = Mapper.CreateMap<Country, CountryDTO>();
        countryMappingExpression.ForMember(dto => dto.Lattitude, mc => mc.MapFrom(e => e.CountryCoordinate.Lattitude));
        countryMappingExpression.ForMember(dto => dto.Longtitude, mc => mc.MapFrom(e => e.CountryCoordinate.Longtitude));

在 Global.asax Application_Start 我有:

        Bootstrapper.Initialise();

在 Bootstrapper 中我有:

public static class Bootstrapper
{
    private static IUnityContainer _container;

    public static IUnityContainer Current
    {
        get
        {
            return _container;
        }
    }

    public static void Initialise()
    {
        var container = BuildUnityContainer();

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }

    private static IUnityContainer BuildUnityContainer()
    {
        _container = new UnityContainer();

        _container.RegisterType(typeof(BoundedContextUnitOfWork), new PerResolveLifetimeManager());

        _container.RegisterType<ICountryRepository, CountryRepository>();  

        _container.RegisterType<ITypeAdapterFactory, AutomapperTypeAdapterFactory>(new ContainerControlledLifetimeManager());

        _container.RegisterType<ICountryAppService, CountryAppServices>(); 

        EntityValidatorFactory.SetCurrent(new DataAnnotationsEntityValidatorFactory());
        var typeAdapterFactory = _container.Resolve<ITypeAdapterFactory>();
        TypeAdapterFactory.SetAdapter(typeAdapterFactory);

        return _container;
    }
}

我的适配器在哪里:

public class AutomapperTypeAdapter : ITypeAdapter
{
    public TTarget Adapt<TSource, TTarget>(TSource source)
        where TSource : class
        where TTarget : class, new()
    {
        return Mapper.Map<TSource, TTarget>(source);
    }

    public TTarget Adapt<TTarget>(object source) where TTarget : class, new()
    {
        return Mapper.Map<TTarget>(source);
    }
}

而 AdapterFactory 是:

    public AutomapperTypeAdapterFactory()
    {
        //Scan all assemblies to find an Auto Mapper Profile
        var profiles = AppDomain.CurrentDomain
                                .GetAssemblies()
                                .SelectMany(a => a.GetTypes())
                                .Where(t => t.BaseType == typeof(Profile));

        Mapper.Initialize(cfg =>
        {
            foreach (var item in profiles)
            {
                if (item.FullName != "AutoMapper.SelfProfiler`2")
                    cfg.AddProfile(Activator.CreateInstance(item) as Profile);
            }
        });
    }

所以我随机收到“缺少类型映射配置或不受支持的映射”。错误提示:

    public TTarget Adapt<TTarget>(object source) where TTarget : class, new()
    {
        return Mapper.Map<TTarget>(source);
    }

虽然此错误随机发生,但很难调试并查看会发生什么。我搜索了很多没有合适的解决方案。

错误是这样的:

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

映射类型:Country -> CountryDTO MyApp.Domain.BoundedContext.Country -> MyApp.Application.BoundedContext.CountryDTO

目标路径:List`1[0]

来源值:MyApp.Domain.BoundedContext.Country

我的项目是一个 MVC 3 项目,带有 Automapper 2.2 和 Unity IoC..

我将不胜感激任何想法、建议或解决方案,并感谢您的回答。

【问题讨论】:

标签: asp.net-mvc-3 unity-container automapper-2


【解决方案1】:

如果你使用Mapper.AssertConfigurationIsValid();,你会得到更详细的信息:

找到未映射的成员。查看下面的类型和成员。添加一个 自定义映射表达式,忽略,添加自定义解析器,或修改 源/目标类型

无论如何,您必须映射目标模型的所有属性。您缺少 CityDTO 和 ID。这里:

Mapper.CreateMap<City, CityDTO>();

Mapper.CreateMap<Country, CountryDTO>()
    .ForMember(dto => dto.Id, options => options.Ignore())
    .ForMember(dto => dto.Longtitude, mc => mc.MapFrom(e => e.CountryCoordinate.Longtitude))
    .ForMember(dto => dto.Lattitude, mc => mc.MapFrom(e => e.CountryCoordinate.Lattitude));

也许您需要在 City-CityDTO 上进行一些额外的映射,因为您没有指定它们。

【讨论】:

  • 其实我已经用 Mapper.Initialize(m => m.AddProfile()); Mapper.AssertConfigurationIsValid();一切似乎都还好.. 另外我已经映射了 city-cityDto 但还没有在这里编写代码片段,因为它似乎与错误无关,虽然我的 Id 是 Guid,但我不会在我的地图中忽略它。
  • 那么您的实体 - 国家/地区有 ID 吗?那么请写出给你带来麻烦的确切代码。
  • 抱歉,所有实体都派生自一个抽象的 EntityBase,其中定义了 Id。顺便说一句,当我更改一些代码并在浏览器中已打开视图并在构建后进行 F5 刷新时构建它时,似乎出现了此错误。
  • MVC 项目的重建使错误消失。也许这没什么大不了的,但我担心这样的错误是否会在生产中引发。
【解决方案2】:

对我来说,这个错误与我拨打CreateMap&lt;&gt;() 的位置有关。我已将它放在我的 DTO 的静态初始化程序中。当我将CreateMap&lt;&gt;() 调用移到不那么可爱的地方时,一切正常。

【讨论】:

    猜你喜欢
    • 2019-08-10
    • 2015-06-27
    • 1970-01-01
    • 2013-01-18
    • 2019-03-01
    • 2017-04-16
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多