7

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();
    }
}
4

1 回答 1

9

如果您使用接口作为目标类型,AutoMapper 将为您动态创建一个实现(代理)类型。

但是,代理生成仅支持 propertiesIgnoreMe ,因此它会为您的方法抛出这个不太具有描述性的异常。所以你不能忽视你的IgnoreMe方法。

作为一种解决方法,您可以明确指定如何使用ConstructUsing重载之一构造目标对象,在这种情况下 AutoMapper 不会生成代理。

Mapper.CreateMap<IThing, IThing>()
      .ConstructUsing((ResolutionContext c) => new Foo());

或者除非你没有充分的理由,你可以直接映射到Foo

Mapper.CreateMap<IThing, Foo>();
于 2013-06-21T21:06:23.720 回答