1

AutoMapper v 8.1.1 / EF6

In this example, where Owner.CarId = null, OwnerDto.Car is also null. So if the default behavior is null on a nested property, is there a way to handle the equivalent of .DefaultIfEmpty(new CarDto()) in ProjectTo?

In using a ProjectTo map to convert an optional one-to-one database relationship, if the Owner.CarId is NULL, the CarDto property is null. I thought the default behavior (based on how null collections are handled as I didn't see any mention of how nulls would be evaluated in Nested Mappings) was to return a new CarDto object...and then from there, wasn't sure if the properties of that new CarDto object would be their natural default values (i.e. int = 0) or they'd be null.

Source Classes

public class Car
{
    public int Id { get; set; }
    public string Model { get; set; }
}

public class Owner
{
    public int Id { get; set; }
    public Car Car { get; set; }
    public int? CarId { get; set; }
    public string Name { get; set; }
}

Destination Classes

public class CarDto
{
    public int Id { get; set; }
    public string Model { get; set; }
}

public class OwnerDto
{
    public int Id { get; set; }
    public CarDto Car { get; set; }
    public int? CarId { get; set; }
    public string Name { get; set; }
}

Mapping Configuration

new MapperConfiguration(settings =>
{
    settings.CreateMap<Owner, OwnerDto>()
    settings.CreateMap<Car, CarDto>();
});
crichavin
  • 4,672
  • 10
  • 50
  • 95
  • 1
    Have you tried `.ForMember(destination => destination.Car, opt => opt.NullSubstitute(new CarDto())));` on `settings.CreateMap()`? – Fildor Feb 08 '23 at 15:32
  • @LucianBargaoanu I do not want `null`, I'm looking for a new instance of `CarDto` to be created with all properties having their native c# default values. – crichavin Feb 08 '23 at 16:42
  • @Fildor I did, but it did not work either. Note these property names are not the same so I still need to use a `option.MapFrom()` So wasn't sure how to also do a `option.NullSubstitute()` on the same destination property. I just put a second .ForMember line for the same Dest property. Is that right? How do you apply these 2 destination options together? – crichavin Feb 08 '23 at 22:29
  • If you already have a `MapFrom`, just write the null check there. – Lucian Bargaoanu Feb 09 '23 at 05:46
  • @LucianBargaoanu can you be more specifi? This does not work: `option.MapFrom(c => c.Car).NullSubstitute(new Car())`. Making 2 separate ForMember() lines does, i.e. `.ForMember(dest => dest.Car, option => option.MapFrom(c => c.Car)) .ForMember(dest => dest.Car, option => option.NullSubstitute(new Car()))` – crichavin Feb 09 '23 at 18:38

0 Answers0