Global.asax问题中的自动映射配置

时间:2013-12-27 22:55:23

标签: c# asp.net asp.net-mvc asp.net-mvc-4 automapper

我有一个MVC4应用程序(.NET 4.5)。我在这个项目中有两个数据类:

public class Address
{
    public string StreetNumber { get; set; }
    public string StreetName { get; set; }
    public string City { get; set; }
    public string County { get; set; }
    public string State { get; set; }
}

public class OrderDetail
{
    public int Id { get; set; }
    public string StreetNumber { get; set; }
    public string StreetName { get; set; }
    public string City { get; set; }
    public string County { get; set; }
    public string State { get; set; }
    public string CustomerEmail { get; set; }
    public DateTime InsertTimeStamp { get; set; }
    public bool IsProcessed { get; set; }
    public DateTime? ProcessedTimeStamp { get; set; }
}

我正在使用AutoMapper从OrderDetail映射到Address类,如下所示

public class OrderDetailToAddressMappingProfile : Profile
{
    protected override void Configure()
    {
        Mapper.CreateMap<OrderDetail, Address>();
    }
}

public static class AutoMapperMvcConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(x =>
            {
                x.AddProfile<OrderDetailToAddressMappingProfile>();
                x.AddProfile<AddressToPropertyAddressMappingProfile>();
            });
    }
}

我在global.asax类中调用AutoMapperMvcConfiguration.Configure()。当我运行这个应用程序并获得我正在尝试从OrderDetail对象到Address对象的映射的代码时,我得到以下异常:

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

似乎Global.asax类的Application_Start没有被触发。我尝试了以下三点来得出这个结论:

  1. 我尝试通过设置断点进行调试,但代码在global.asax中没有中断。我知道Application_Start只被触发一次所以在调试之前我停止了内部VS Web服务器,但它仍然没有中断。

  2. 我在映射代码之前使用了Mapper.FindTypeMapFor()并返回null。

  3. 如果我在映射代码之前中断并手动调用AutoMapperMvcConfiguration.Configure(),我看不到这个映射问题。

  4. 不确定为什么Application_Start没有触发。我不明白我的MVC应用程序如果没有引发Application_Start就可以运行,因为也从Application_Start调用了路由寄存器方法。

    如果我错过了什么,请告诉我。

    更新1:

    以下是使用映射的代码:

        public ActionResult Process(int orderId)
        {
            OrderDetail orderDetail = _hydrantFlowOrderAccessor.GetHydrantFlowOrderById(orderId);
    
            if (orderDetail != null)
            {
                Address address = Mapper.Map<OrderDetail, Address>(orderDetail);
                GeoLocation geoLocation = _geoDataAccessor.GetGeoLocation(Mapper.Map<Address, PropertyAddress>(address));
    
                IEnumerable<FlowTest> flowTests =
                    _hydrantFlowDataAccessor.GetFlowTestByAddress(address);
    
                Process processModel = new Process
                {
                    FlowTests = flowTests,
                    StreetName = address.StreetName,
                    Latitude = geoLocation.Latitude,
                    Longitude = geoLocation.Longitude
                };
    
                return View(processModel);
            }
    
            return null;
        }
    

    堆栈追踪:

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

    映射类型: OrderDetail - &gt;地址 ISO.NPCEfficiencies.DashBoard.Models.HydrantFlows.OrderDetail - &gt; ISO.NPCEfficiencies.DashBoard.Models.HydrantFlows.Address

    目的地路径: 地址

    来源价值: ISO.NPCEfficiencies.DashBoard.Models.HydrantFlows.OrderDetail]    AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context)+861    AutoMapper.MappingEngine.Map(对象源,类型sourceType,类型destinationType,动作1 opts) +196 AutoMapper.MappingEngine.Map(TSource source) +257 AutoMapper.Mapper.Map(TSource source) +107 ISO.NPCEfficiencies.DashBoard.Controllers.HydrantFlowController.Process(Int32 orderId) in g:\Projects\Visual Studio 2012\NPCDashBoard\ISO.NPCEfficiencies.DashBoard\Controllers\HydrantFlowController.cs:60 lambda_method(Closure , ControllerBase , Object[] ) +161 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary 2个参数)+211    System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext,ActionDescriptor actionDescriptor,IDictionary 2 parameters) +27 System.Web.Mvc.<>c__DisplayClass13.<InvokeActionMethodWithFilters>b__10() +55 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func 1 continuation)+253    System.Web.Mvc。&lt;&gt; c_ DisplayClass15.b _12()+21    System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext,IList 1 filters, ActionDescriptor actionDescriptor, IDictionary 2个参数)+191    System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext,String actionName)+324    System.Web.Mvc。&lt;&gt; c_ DisplayClass1d.b _19()+23    System.Web.Mvc.Async。&lt;&gt; c_ DisplayClass1.b _0()+19    System.Web.Mvc.Async。&lt;&gt; c_ DisplayClass8 1.<BeginSynchronous>b__7(IAsyncResult _) +10 System.Web.Mvc.Async.WrappedAsyncResult 1.End()+62    System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)+57    System.Web.Mvc.Async。&lt;&gt; c _DisplayClass4.b__3(IAsyncResult ar)+23    System.Web.Mvc.Async.WrappedAsyncResult 1.End() +62 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult 1.End()+62    System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)+47    System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)+9    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()+9629708    System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean&amp; completedSynchronously)+155

    更新2:

    Global.asax中

    public class MvcApplication : SpringMvcApplication
    {
        protected void Application_Start()
        {
            AutoMapperMvcConfiguration.Configure();
    
            AreaRegistration.RegisterAllAreas();
    
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
    

1 个答案:

答案 0 :(得分:2)

我尝试将Application_Start方法的签名更改为

public void Application_Start(object sender, EventArgs e)

正如@WiktorZychla所建议但我得到一个警告,它在SpringMvcApplication类中隐藏了相同的方法。然后我尝试通过将方法签名更改为

来覆盖SpringMvcApplication中的Application_Start虚拟方法
protected override void Application_Start(object sender, EventArgs e) 

这就是诀窍。