0

First up this is not a duplicate of AutoMapper mapping properties with private setters , because that deals with 'properties with private setters' not readonly setters. Although I would be happy to merge, if needed.

public class Example{

 public string PrivateSetter { get; private set;}
 public string ReadonlyProperty { get; }

}

Now that nullable reference types is a thing. I want to create dtos/models that follow that practice. however if I have a class with a property of say public string Name { get; set; } I get warnings that Name may be null. So I thought I would change the property to be a readonly property public string Name { get; } which I initialize in the constructor. Sweet! That made my null warning go away. But boom now at runtime my auto mapper dies. It cant find a parameterless constructor.

Now one way around this is to setup my mapper like this:


public class SourceClass
{
  public string Name { get; }
}

public class DestinationClass
{

  public DestinationClass(string name)
  { 
    Name = name; 
  }

  public string Name { get; }
}

Mapper.CreateMap<SourceClass, DestinationClass>()
            .ConstructUsing(s => new DestinationClass(s.Name));

However that is pretty rubbish! As I now need to manually map every property, in the correct order, in the .ConstructUsing() method. Which kinda defeats the point of using Automapper.

So my question is How can I map to a class, with read only properties, using Automapper; without having to use .ConstructUsing()` and manually map every property into the constructor?

DarcyThomas
  • 1,218
  • 13
  • 30

0 Answers0