【问题标题】:Map readonly fields with Automapper使用 Automapper 映射只读字段
【发布时间】:2014-10-28 06:30:22
【问题描述】:

我在不同的命名空间中有两个相同的类:

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

和命名空间ClassLibrary2中相同的类定义。

当我尝试使用 AutoMapper 时,我得到了这个异常:

表达式必须是可写的参数名称:left

这是AutoMapper的代码:

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

但是如果我尝试这个AutoMapper Exclude Fields 它不起作用,使用这个:

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

当然可以将其更改为具有公共 get 和私有集的属性(如在 Automapper ignore readonly properties 中),但我想防止未来的开发人员在构造函数之后设置值。

有没有办法使用 AutoMapper 解决这个问题?

【问题讨论】:

标签: c# automapper


【解决方案1】:

如果您想在构造函数中设置属性,请使用.ConstructUsing,然后忽略该字段:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    相关资源
    最近更新 更多