Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip mapping null properties

Tags:

c#

automapper

I'm using AutoMapper to map a ViewModel to a Model. However, I want properties to not be mapped if the corresponding source property is null.

My source class is as follows:

public class Source
{
    //Other fields...
    public string Id { get; set; } //This should not be mapped if null
}

And the destination class is:

public class Destination
{
    //Other fields...
    public Guid Id { get; set; }
}

And here is how I configured the mapper:

Mapper.Initialize(cfg =>
{
    //Other mappings...
    cfg.CreateMap<Source, Destination>()
        .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));
});

I thought that mapping would mean that properties don't get overwritten in the destination if the source one is null. But apparently I'm wrong: even when Source.Id is null, it still gets mapped, AutoMapper assigns it an empty Guid (00000000-0000-0000-0000-000000000000), overwriting the existing one. How do I properly tell AutoMapper to skip mapping of a property if the source is null?

NOTE: I don't think this is a problem with the Guid<->String conversion, such conversion works in automapper, I've used it in the pass. The problem is that it's not skipping the Id property when it is null.

like image 770
Master_T Avatar asked Sep 07 '17 14:09

Master_T


1 Answers

The easy way would be to not have to distinguish between null and Guid.Empty. Like this

    cfg.CreateMap<Source, Destination>()
        .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => ((Guid)srcMember) != Guid.Empty));

In this case the source member is not the string value you map from, it's the resolved value that would be assigned to the destination. It's of type Guid, a struct, so it will never be null. A null string will map to Guid.Empty. See here.

like image 117
Lucian Bargaoanu Avatar answered Nov 03 '22 23:11

Lucian Bargaoanu