Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper null properties

Tags:

c#

automapper

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.
like image 460
Andrew Kalashnikov Avatar asked Jun 21 '10 09:06

Andrew Kalashnikov


People also ask

How do I ignore properties in AutoMapper?

So, the AutoMapper Ignore() method is used when you want to completely ignore the property in the mapping. The ignored property could be in either the source or the destination object.

Does AutoMapper map private properties?

By default, AutoMapper only recognizes public members. It can map to private setters, but will skip internal/private methods and properties if the entire property is private/internal.

Is AutoMapper faster than manual mapping?

Inside this article, it discusses performance and it indicates that Automapper is 7 times slower than manual mapping. This test was done on 100,000 records and I must say I was shocked.

Is AutoMapper case sensitive?

Automatically-mapped Properties are now case sensitive · Issue #950 · AutoMapper/AutoMapper · GitHub.


1 Answers

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))
      ;
like image 64
Jakob Christensen Avatar answered Nov 11 '22 21:11

Jakob Christensen