Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

c# - Automapper null properties

I map my objects to dtos with Automapper.

public class OrderItem : BaseDomain
{
    public virtual Version Version { get; set; }
    public virtual int Quantity { get; set; }
}




[DataContract]
[Serializable]
public class OrderItemDTO
{
    [DataMember]
    public int Id { get; set; }
    [DataMember]
    public string Guid { get; set; }
    [DataMember]
    public virtual int? VersionId { get; set; }
    [DataMember]
    public virtual string VersionName { get; set; }
    [DataMember]
    public virtual int Quantity { get; set; }

}

So when I have OrderItem with null version, i get an exception at:

 Mapper.Map<OrderItem, OrderItemDTO>(item)

 Missing type map configuration or unsupported mapping.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Without having seen your mapping code it is hard to say exactly what is going wrong but my guess is that you are mapping your types with code similar to the following:

Mapper.CreateMap<OrderItem, OrderItemDTO>()
      .ForMember(dest => dest.VersionId, options => options.MapFrom(orderitem => orderitem.Version.VersionId))
      .ForMember(dest => dest.VersionName, options => options.MapFrom(orderitem => orderitem.Version.VersionName))
      ;

The code above will fail when OrderItem.Version is null. To prevent this you can check for null in the delegates passed to ForMember:

Mapper.CreateMap<OrderItem, OrderItemDTO>()
      .ForMember(dest => dest.VersionId, options => options.MapFrom(orderitem => orderitem.Version == null ? (int?) null : orderitem.Version.VersionId))
      .ForMember(dest => dest.VersionName, options => options.MapFrom(orderitem => orderitem.Version == null ? null : orderitem.Version.VersionName))
      ;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...