Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper - map a property without a `set;` implementation

Tags:

c#

automapper

Is there some way to map a IList<> property which does not have a set; method?

Source Class:

public class SourceClass
{
    private IList<string> strings;

    public IList<string> Strings { get { return this.strings; } }

    public SourceClass() { this.strings = new List<string>() { "s1", "s2", "s3" };
    //...
}

Destionation Class:

public class DestinationClass
{
    private IList<string> strings;

    public IList<string> Strings { get { return this.strings; } }

    public DestinationClass() { this.strings = new List<string>();
    //...
}

As you can see, neither class has set; implemented. The result is that when I perform AutoMapper.Mapper.Map<SourceClass, DestinationClass>(source, destination), the Strings property is empty.

The obvious solution is to provide a set; implementation is DestinationClass, however, I would like to know how to provide a custom configuration in order to deal with these troubles.

Currently, my configuration is:

public class XProfile : AutoMapper.Profile
{
    protected override void Configure()
    {
        AutoMapper.Mapper.CreateMap<SourceClass, DestinationClass>();
    }
}
like image 992
Jordi Avatar asked Nov 17 '25 08:11

Jordi


2 Answers

You could create a constructor like this.

public class DestinationClass
{
    private IList<string> strings;

    public IList<string> Strings { get { return this.strings; } }

    public DestinationClass() : this(new List<string>()) { }

    public DestinationClass(IList<string> strs) {
        strings = strs.ToList(); // clone it
    }
    //...
}

Then you can make the mapping with the ConstructUsing method, to tell AutoMapper to call the constructor that you created.

public class XProfile : AutoMapper.Profile
{
    protected override void Configure()
    {
        AutoMapper.Mapper.CreateMap<SourceClass, DestinationClass>()
            .ConstructUsing(x => new DestinationClass(x.Strings));
    }
}
like image 121
Frank Bryce Avatar answered Nov 18 '25 23:11

Frank Bryce


You can configure AutoMapper to recognize non-public members. Check out the documentation

like image 32
Martino Bordin Avatar answered Nov 18 '25 23:11

Martino Bordin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!