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?
如果您想在构造函数中设置属性,请使用.ConstructUsing ,然后忽略该字段: 
Mapper.CreateMap<ClassLibrary1.Class1, ClassLibrary2.Class1>()
    .ConstructUsing(cls1 => new ClassLibrary2.Class1(cls1.field1))
    .ForMember(a => a.field1, a => a.Ignore());
                        链接地址: http://www.djcxy.com/p/37388.html
                        上一篇: 使用AutoMapper进行嵌套对象映射
下一篇: 使用Automapper映射只读字段
