How can I use AutoMapper on properties marked Internal?

前端 未结 3 513
借酒劲吻你
借酒劲吻你 2021-01-13 06:44

I have a solution with several projects. A business components project, an MVC web app, a DTO\'s and ViewModels project, a business component unit test project, and an MVC u

相关标签:
3条回答
  • 2021-01-13 07:16

    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.

    0 讨论(0)
  • 2021-01-13 07:19

    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.

    0 讨论(0)
  • 2021-01-13 07:41

    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.
        }
    }
    
    0 讨论(0)
提交回复
热议问题