简体   繁体   中英

Map readonly fields with 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?

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM