[英]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
. 名称空间
ClassLibrary2
的相同类定义。
When I try to use AutoMapper, I get this exception: 当我尝试使用AutoMapper时,我得到以下异常:
Expression must be writeable Parameter name: left
表达式必须是可写的参数名称:left
This is the code of AutoMapper: 这是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: 但是,如果我尝试使用此AutoMapper排除字段它不起作用,使用此:
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. 当然,它可以将它更改为具有公共get和private设置的属性(比如在Automapper中忽略readonly属性 ),但我想阻止将来的开发人员在构造函数之后设置值。
Is there any way of solving this using AutoMapper? 有没有办法使用AutoMapper解决这个问题?
If you'd like to set the property in the constructor, use .ConstructUsing
and then ignore the field: 如果您想在构造函数中设置属性,请使用
.ConstructUsing
,然后忽略该字段:
Mapper.CreateMap<ClassLibrary1.Class1, ClassLibrary2.Class1>()
.ConstructUsing(cls1 => new ClassLibrary2.Class1(cls1.field1))
.ForMember(a => a.field1, a => a.Ignore());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.