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))
If you have any questions or suggestions feel free to rate this snippet, post a comment or Contact Us via Email.
Related links:
- AutoMapper
- Automapper: Map to Protected Property
- Configuring visibility
- Before and after map actions (Automapper WIKI)
- Access Modifiers (C# Programming Guide)
- Access Levels in Visual Basic
RT @CodeSnippetsNET: Map to Protected Property using #Automapper in C# and #VB .NET http://t.co/T3uKSISKp0 #csharp #dotnet #programming #co…
RT @CodeSnippetsNET: Map to Protected Property using #Automapper in C# and #VB .NET http://t.co/T3uKSISKp0 #csharp #dotnet #programming #co…
RT @CodeSnippetsNET: Map to Protected Property using #Automapper in C# and #VB .NET http://t.co/T3uKSISKp0 #csharp #dotnet #programming #co…
How to Map to Protected Property using Automapper in #CSharp and #VBNET http://t.co/T7B8pitQGm via @CodeSnippetsNET #dotnet