' AutoMapper.AutoMapperMappingException'发生在AutoMapper.dll中

时间:2015-02-01 03:43:40

标签: c# asp.net-mvc automapper

 public class ClientViewModel
    {
        [Required(ErrorMessage = "The Client Code field is required.")]  
        public string ClientCode { get; set; }
        [Required(ErrorMessage = "The Company Legal Name field is required.")]  
        public string CompanyLegalName { get; set; }
        public string Notes { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
        public Nullable<DateTime> ScheduledDate { get; set; }
        public Nullable<decimal> AmountDiscount { get; set; }
    }

    public class Client
    {
        public string ClientCode { get; set; }   
        public string CompanyLegalName { get; set; }
        public string Notes { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
        public Nullable<DateTime> ScheduledDate { get; set; }
        public Nullable<decimal> AmountDiscount { get; set; }
    }

编辑:

  

异常详细信息:AutoMapper.AutoMapperMappingException:缺少类型   地图配置或不支持的映射。

     

映射类型:客户端 - &gt; ClientViewModel myapp.Models.Client - &gt;   myapp.Models.ClientViewModel

     

目标路径:ClientViewModel

     

来源价值:myapp.Models.Client

我的Client&amp; ClientViewModel具有完全相同数量的道具,下面是我正在使用的代码及其抛出错误,但没有获得太多信息,我在这里缺少什么?

Client client = context.Clients.Where(x => x.CustomerID == id).FirstOrDefault();
ClientViewModel clientViewModel = Mapper.Map<Client, ClientViewModel>(client);
  

发生了“AutoMapper.AutoMapperMappingException”类型的异常   在AutoMapper.dll中但未在用户代码中处理

2 个答案:

答案 0 :(得分:5)

您忘记创建地图了。将其添加到您的代码中(在调用Mapper类之前):

Mapper.CreateMap<Client, ClientViewModel>();
ClientViewModel cvm = Mapper.Map<Client, ClientViewModel>(client);

Working demo on dotnetfiddle

答案 1 :(得分:2)

在调用Map之前。您需要调用CreateMap:

Mapper.CreateMap<Client, ClientViewModel>();

通常,您可以在应用程序初始化代码/类中调用它,例如在global.asax.cs中。