winter
winter

Reputation: 35

use AutoMapper.EF6,but Mapper not initialized error happed

the error info :

Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance. InnerException: StackTrace: at AutoMapper.Mapper.get_Configuration()

the asp.net mvc5 controller code

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

AutoMapper Configure Code

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

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

Register Code

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

i home return data type is IQueryable in the controller,not List, I See the Question and Issue in stackoverflow but could not solved my problem.

Upvotes: 0

Views: 1256

Answers (1)

Alex Tsvetkov
Alex Tsvetkov

Reputation: 1659

From AutoMapper's source code you can see that this exception will be thrown when configuration is not initialized at all:

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

Make sure that Mapper is correctly configured using static properties or correctly registered using IoC container if you are using that (please, refer to documentation for details). Are you perhaps missing the Mapper.Initialize() call?

Upvotes: 1

Related Questions