AutoMapper mapping properties with private setters

孤者浪人 提交于 2019-12-17 20:03:55

问题


Is it possible to assign properties with private setters using AutoMapper?


回答1:


If you set the value for this properties in the constructor like this

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

    public string Name { get; private set; }
}

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

then you can use ConstructUsing like this

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

which works with this code

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



回答2:


AutoMapper allows now (I am not sure, since when) to map properties with private setters. It is using reflection for creating objects.

Example classes:

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


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

And mapping:

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 will map property with private setter with no problem. If you want to force encapsulation, you need to use IgnoreAllPropertiesWithAnInaccessibleSetter. With this option, all private properties (and other inaccessible) will be ignored.

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

The problem will emerge, if you will use Silverlight. According to 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.




回答3:


See #600 Private/internal destination properties.

Solution:

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


来源:https://stackoverflow.com/questions/8355024/automapper-mapping-properties-with-private-setters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!