【问题标题】:use AutoMapper.EF6,but Mapper not initialized error happed使用 AutoMapper.EF6,但 Mapper 未初始化错误发生
【发布时间】:2017-06-11 18:39:38
【问题描述】:

错误信息:

映射器未初始化。使用适当的调用初始化 配置。如果您尝试通过 容器或其他方式,请确保您没有对 静态 Mapper.Map 方法,如果您使用的是 ProjectTo 或 UseAsDataSource 扩展方法,确保传入 适当的 IConfigurationProvider 实例。内部异常: StackTrace:在 AutoMapper.Mapper.get_Configuration()

asp.net mvc5 控制器代码

public override ActionResult Kendo_Read(DataSourceRequest request, IQueryable<Activity> results)
{
    var data = results.ProjectTo<ActivityViewModel>();
    var rdata = data.ToDataSourceResult(request);
    return Json(rdata);
}

AutoMapper 配置代码

public class CRMProfile : Profile
{
  CreateMap<Activity, ActivityViewModel>();
}

public static class Configuration
{
   public static MapperConfiguration MapperConfiguration()
   {
        return new MapperConfiguration(x =>
        {
            x.AddProfile(new CRMProfile());
        }
   }
}

注册码

internal static MapperConfiguration MapperConfiguration { get; private set; }
public class MvcApplication : System.Web.HttpApplication
{
      MapperConfiguration = Configuration.MapperConfiguration();
}

i home return 数据类型在控制器中是 IQueryable,而不是 List, 我在 stackoverflow 中看到了 Question 和问题,但无法解决我的问题。

【问题讨论】:

    标签: c# asp.net-mvc automapper


    【解决方案1】:

    AutoMapper's source code可以看出,配置完全没有初始化的时候会抛出这个异常:

    public static IConfigurationProvider Configuration
    {
        get => _configuration ?? throw new InvalidOperationException(InvalidOperationMessage);
        private set => _configuration = value;
    }
    

    确保Mapper 使用静态属性正确配置或使用IoC 容器正确注册(如果您正在使用它,请参阅documentation 了解详细信息)。您是否错过了Mapper.Initialize() 电话?

    【讨论】:

      猜你喜欢
      • 2019-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-20
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      相关资源
      最近更新 更多