How can I use AutoMapper on properties marked Internal?

不羁的心 提交于 2019-12-01 09:19:33
CShark

Just set the ShouldMapProperty property of your configuration object in the initialize method.

Here is an example using the static API, however, you should be able to achieve the same in a similar fashion by using the non-static API.

Mapper.Initialize(i =>
{
    i.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsAssembly;
    i.CreateMap<Source, Target>();                
});

If you use a profile, this must go in the constructor:

public class MyProfile : Profile
{
    public MyProfile()
    {
        ShouldMapProperty = arg => arg.GetMethod.IsPublic || arg.GetMethod.IsAssembly;

        // The mappings here.
    }
}

Use this. It works on private and internal fields just fine.

http://ragingpenguin.com/code/privatefieldresolver.cs.txt

usage:

// in one library
public class Foo
{
internal string _bar = "some value";
}

// in another library
public class FooModel
{
public string Bar { get; set; }
}

Mapper.CreateMap<Foo, FooModel>()
.ForMember(x => x.Bar, o => o.ResolveUsing(new PrivateFieldResolver("_bar")));

Works like a charm.

Have you thought about mapping to interfaces instead? Have the data contract implement an interface, and then just map to that. You could then explicitly implement the interface, effectively hiding those members.

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