11

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.
Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
Andrew Kalashnikov
  • 3,073
  • 5
  • 34
  • 57

1 Answers1

25

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))
      ;
Jakob Christensen
  • 14,826
  • 2
  • 51
  • 81
  • 5
    I thought automapper would be smart enough to handle null properties – Jordan Jul 20 '11 at 16:21
  • 7
    @Jordan: When you create your own mapping to flatten your structure as in the above example where you use the lambda "orderitem => orderitem.Version.VersionId" and orderitem.Version is null, AutoMapper has no way to detect that there is a problem in the lambda. – Jakob Christensen Jul 20 '11 at 16:24
  • What version are you using here? – Jimmy Bogard Sep 30 '12 at 22:13
  • I think that your second ForMember wouldn't compile bacause of some error like "There's no implicit conversion between...". Would by necessary to cast null. – M. Pipal Nov 29 '16 at 08:26
  • 1
    Why I cannot use `options.MapFrom(orderitem => orderitem.Version?.VersionName)`? – ADM-IT Oct 06 '21 at 15:29
  • You can. But the ?. operator didn't exist when I wrote this answer back in 2010. – Jakob Christensen Oct 06 '21 at 16:11