AutoMapper映射属性与私有setter

时间:2011-12-02 10:37:32

标签: automapper private setter

是否可以使用AutoMapper为私有设置器分配属性?

3 个答案:

答案 0 :(得分:18)

如果在构造函数中设置此属性的值,就像这样

public class RestrictedName
{
    public RestrictedName(string name)
    {
        Name = name;
    }

    public string Name { get; private set; }
}

public class OpenName
{
    public string Name { get; set; }
}

然后您可以像这样使用ConstructUsing

Mapper.CreateMap<OpenName, RestrictedName>()
            .ConstructUsing(s => new RestrictedName(s.Name));

使用此代码

var openName = new OpenName {Name = "a"};
var restrictedName = Mapper.Map<OpenName, RestrictedName>(openName);
Assert.AreEqual(openName.Name, restrictedName.Name);

答案 1 :(得分:14)

AutoMapper现在允许(我不确定,从何时开始)使用私有设置器映射属性。它使用反射来创建对象。

示例类:

public class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
}


public class PersonDto
{
    public string Fullname { get; private set; }
}

并映射:

AutoMapper.Mapper.CreateMap<Person, PersonDto>()
    .ForMember(dest => dest.Fullname, conf => conf.MapFrom(src => src.Name + " " + src.Surname));

var p = new Person()
{
    Name = "John",
    Surname = "Doe"
};

var pDto = AutoMapper.Mapper.Map<PersonDto>(p);

AutoMapper将使用私有setter映射属性没有问题。如果要强制封装,则需要使用IgnoreAllPropertiesWithAnInaccessibleSetter。使用此选项,将忽略所有私有属性(以及其他不可访问的属性)。

AutoMapper.Mapper.CreateMap<Person, PersonDto>()
    .ForMember(dest => dest.Fullname, conf => conf.MapFrom(src => src.Name + " " + src.Surname))
    .IgnoreAllPropertiesWithAnInaccessibleSetter();

如果您使用Silverlight,问题就会出现。根据MSDN:https://msdn.microsoft.com/en-us/library/stfy7tfc(v=VS.95).aspx

In Silverlight, you cannot use reflection to access private types and members. 

答案 2 :(得分:3)

请参阅#600 Private/internal destination properties

解决方案:

public class PrivateInternalProfile {
    protected override Configure() {
        ShouldMapField = fieldInfo => true;
        ShouldMapProperty = propertyInfo => true;
        CreateMap<User, UserDto>(); //etc
    }
}