I am new to Automapper, so I am not sure if this is possible.
I would like to map a class, but get it to ignore methods that are void. Below is an illustration of the code I have. When I run this I get the following exception message.
An unhandled exception of type 'AutoMapper.AutoMapperMappingException' occurred in AutoMapper.dll
Unfortunately it isn't an option to change the interface, so I assume if this is possible there is some sort of configuration I am missing?
public interface IThing
{
string Name { get; set; }
void IgnoreMe();
}
public class Foo : IThing
{
public string Name { get; set; }
public void IgnoreMe()
{
}
}
class Program
{
static void Main(string[] args)
{
var fooSource = new Foo {Name = "Bobby"};
Mapper.CreateMap<IThing, IThing>();
var fooDestination = Mapper.Map<IThing>(fooSource);
Console.WriteLine(fooDestination.Name);
Console.ReadLine();
}
}
If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.
So, the AutoMapper Ignore() method is used when you want to completely ignore the property in the mapping. The ignored property could be in either the source or the destination object.
How AutoMapper works? AutoMapper internally uses a great concept of programming called Reflection. Reflection in C# is used to retrieve metadata on types at runtime. With the help of Reflection, we can dynamically get a type of existing objects and invoke its methods or access its fields and properties.
AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.
If you are using an interface as a destination type AutoMapper will dynamically create an implementation (proxy) type for you.
However the proxy generation only supports properties, so it throws this not too descriptive exception for your IgnoreMe
method. So you cannot ignore your IgnoreMe
method.
As a workaround you can explicitly specify how the destination objects should be constructed with using one of the ConstructUsing
overloads in this case AutoMapper does not generate proxies.
Mapper.CreateMap<IThing, IThing>()
.ConstructUsing((ResolutionContext c) => new Foo());
Or unless you have no good reason, you can directly map to Foo
Mapper.CreateMap<IThing, Foo>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With