Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map readonly fields with Automapper

Tags:

c#

automapper

I have two identical classes in different namespaces:

namespace ClassLibrary1
class Class1
{
    public readonly int field1;
    public Class1(int value) { field1 = value; }
}

And the same class definition in namespace ClassLibrary2.

When I try to use AutoMapper, I get this exception:

Expression must be writeable Parameter name: left

This is the code of AutoMapper:

Mapper.CreateMap<ClassLibrary1.Class1, ClassLibrary2.Class1>();
var result = Mapper.Map<ClassLibrary2.Class1>(class1);

But if I try this AutoMapper Exclude Fields it doesn't work, using this:

Mapper.CreateMap<ClassLibrary1.Class1, ClassLibrary2.Class1>()
    .ForMember(a => a.field1, a => a.Ignore());

For sure it works to change it to a property with public get and private set (like in Automapper ignore readonly properties), but I want to prevent a future developer of setting the value after constructor.

Is there any way of solving this using AutoMapper?

like image 888
Marlos Avatar asked Jan 10 '23 21:01

Marlos


1 Answers

If you'd like to set the property in the constructor, use .ConstructUsing and then ignore the field:

Mapper.CreateMap<ClassLibrary1.Class1, ClassLibrary2.Class1>()
    .ConstructUsing(cls1 => new ClassLibrary2.Class1(cls1.field1))
    .ForMember(a => a.field1, a => a.Ignore());
like image 54
Andrew Whitaker Avatar answered Jan 19 '23 02:01

Andrew Whitaker