To map protected Properties using AutoMapper in C# and VB.NET you can use the following snippet.

Samples

Samples C#

using System;
using AutoMapper;

namespace de.Fesslersoft.AutoMapperMapToProtectedProperties
{
    class Program
    {
        static void Main(string[] args)
        {
            Product prod = new Product {Number = "Test", Price = 100, Quantity = 50};
            Mapper.Initialize(cfg =>
            {
                //without this line the ItemQuantity will be 10 and the Price 5
                //with this line  the ItemQuantity will be 50 and the Price 100
                cfg.ShouldMapProperty = p => p.GetGetMethod(true).IsPrivate || p.GetGetMethod(true).IsHideBySig;
                Mapper.CreateMap<Product, Item>();
            });
            Item item = Mapper.Map<Product, Item>(prod);
            Console.WriteLine("ItemNumber: {0}; ItemQuantity: {1}, ItemPrice: {2}", item.Number, item.GetQuantity(), item.GetPrice());
            Console.Read();
        }

        public class Product
        {
            public string Number { get; set; }
            public short Quantity { get; set; }
            public decimal Price { get; set; }
        }

        public class Item
        {
            public Item()
            {
                Quantity = 10;
                Price = 5;
            }

            public string Number { get; set; }

            protected short Quantity { get; set; }
            private decimal Price { get; }

            public decimal GetPrice()
            {
                return Price;
            }

            public short GetQuantity()
            {
                return Quantity;
            }
        }
    }
}

Samples VB.NET

🙁 missing, feel free to provide a VB.NET sample

Another approach would be to create a method in the destination object to do the mapping.

Samples

Sample C#

Mapper.CreateMap<Source, Destination>().AfterMap((src, dest) => dest.MethodToSetProtectedProperty(Source.SourceProperty));

Sample VB.NET

Mapper.CreateMap(Of Source, Destination)().AfterMap(Function(src, dest) dest.MethodToSetProtectedProperty(Source.SourceProperty))

 

Compatibility: working .NET 2.0 working .NET 3.0 not tested .NET 3.5 not working .NET 4.0 not working .NET 4.5not working .NET 4.6

If you have any questions or suggestions feel free to rate this snippet, post a comment or Contact Us via Email.

Related links:

 

4 thought on “How to Map to Protected Property using AutoMapper in C# and VB.NET”

Leave a Reply