问题
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();
}
}
回答1:
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>();
来源:https://stackoverflow.com/questions/17243693/can-automapper-ignore-void-methods