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?
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With