AutoMapper不工作**可能导致导航属性失败**

时间:2013-04-05 06:52:12

标签: asp.net-mvc-4 automapper

我有两个班级:

  

类 - 国家>> ID,名称,列表

     

类 - 城市>> ID,名称,国家/地区ID,国家/地区

我有与上述类相同的CountryViewModel和CityViewModel类。

我在Global.asax.cs中写了以下内容:

AutoMapper.Mapper.CreateMap<Country,CountryViewModel>();
AutoMapper.Mapper.CreateMap<City,CityViewModel>();

从datbabse中检索实体后,我正在触发以下行来映射模型以查看模型。:

AutoMapper.Mapper.Map(country, System.Type.GetType("Country"), System.Type.GetType("CountryViewModel"));

这是在上面的行中给出“找不到对象引用”错误。

1 个答案:

答案 0 :(得分:2)

  1. 确保您的global.asax.cs还包含对AutoMapper.Mapper.AssertConfigurationIsValid()的调用,以确保所有内容都已正确映射。

  2. 我以前从未使用Map的非通用语法,但应该使用的通用版本是:

    AutoMapper.Mapper.Map<Country, CountryViewModel>(country);