2016-08-18 40 views
0

我正在使用Asp.Net Web API創建POC。爲了將一個對象類型映射到另一個對象,我使用AutoMapper(v5.1.1)。這裏是正在使用的映射類型:AutoMapperConfigurationException:AutoMapper拋出異常而不顯示屬性名稱

//Entity 
public class Goal : IVersionedEntity 
    { 
     public virtual int GoalId { get; set; } 
     public virtual string Title { get; set; } 
     public virtual string Description { get; set; } 
     public virtual DateTime StartDate { get; set; } 
     public virtual DateTime EndDate { get; set; } 
     public virtual string Reward { get; set; } 
     public virtual DateTime? DisabledDate { get; set; } 
     public virtual byte[] Version { get; set; } 
     public virtual User User { get; set; } 
     public virtual ICollection<Schedule> Schedules { get; set; } 
    } 
//Model 
public class Goal 
    { 
     private List<Link> _links; 
     public int GoalId { get; set; } 
     public string Title { get; set; } 
     public string Description { get; set; } 
     public DateTime? StartDate { get; set; } 
     public DateTime? EndDate { get; set; } 
     //public Status Status { get; set; } 
     public string Reward { get; set; } 
     public DateTime? DisabledDate { get; set; } 
     public User User { get; set; } 
     public ICollection<Schedule> Schedules { get; set; } 
     public List<Link> Links 
     { 
      get { return _links ?? (_links = new List<Link>()); } 
      set { _links = value; } 
     } 
     public void AddLink(Link link) 
     { 
      _links.Add(link); 
     } 

    } 

我映射目標實體到目標模型對象類型如下:

public async System.Threading.Tasks.Task Configure() 
     { 
      Mapper.Initialize(cfg => cfg.CreateMap<Data.Entities.Goal, Models.Goal>() 
      .ForMember(m => m.Links, i => i.Ignore())); 
     } 

這裏是「AutoMapperConfigurator」類「App_Start」 :

public void Configure(IEnumerable<IAutoMapperTypeConfigurator> autoMapperTypeConfigurations) 
     { 
      autoMapperTypeConfigurations.ToList().ForEach(m => m.Configure()); 
      Mapper.AssertConfigurationIsValid(); 
     } 

但它拋出以下異常:

映射的TestApp.Web.Api.Models.Goal上的以下屬性不能爲 映射:添加自定義映射表達式,忽略,添加自定義 解析程序或修改目標類型TestApp.Web.Api.Models.Goal。 上下文:從類型TestApp.Data.Entities.Goal映射到 TestApp.Web.Api.Models.Goal類型爲 的異常拋出了'AutoMapper.AutoMapperConfigurationException'。

看到它沒有顯示哪個屬性沒有被映射。 任何幫助這個問題。

回答

0

願意花小時後,我的最終調查結果如下:

  1. 你必須把所有的實體模型和服務模型映射正確,使其工作。即使失敗了,也會拋出上述異常。如果你的複雜類型映射不正確,你會得到上述錯誤。
  2. 就我而言,我錯過了如何配置Complex TypeAutoMapper
  3. 要配置Complex Type,無論是添加.ForMember(m => m.Property, i => i.Ignore())忽略複雜類型映射如果不需要或.ForMember(m => m.Property, i => i.MapFrom(j => Mapper.Map<Entity,ServiceModel>(j.Property)))嵌套映射(參閱:http://www.softwarerockstar.com/2011/05/complex-object-mapping-using-automapper/),或使用CustomMapping如果存在映射
期間來具體要求