我正在使用Asp.Net Web API创建POC。为了将一种对象类型映射到另一种,我正在使用AutoMapper(v5.1.1)。以下是用于映射的类型:
//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()));
}
这是&#39; AutoMapperConfigurator&#39;在App_Start&#39;:
中开课public void Configure(IEnumerable<IAutoMapperTypeConfigurator> autoMapperTypeConfigurations)
{
autoMapperTypeConfigurations.ToList().ForEach(m => m.Configure());
Mapper.AssertConfigurationIsValid();
}
但它抛出以下异常:
TestApp.Web.Api.Models.Goal上的以下属性不能 mapped:添加自定义映射表达式,忽略,添加自定义 解析器,或修改目标类型TestApp.Web.Api.Models.Goal。 上下文:从TestApp.Data.Entities.Goal类型映射到 TestApp.Web.Api.Models.Goal类型异常 &#39; AutoMapper.AutoMapperConfigurationException&#39;被扔了。
看到它没有显示哪些属性未被映射。 对此有任何帮助。
答案 0 :(得分:0)
花了好几个小时后,我的最终调查结果如下:
Complex Type
配置AutoMapper
。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/)或使用{{1如果在映射期间有特定要求