Automapper可以忽略void方法吗? [英] Can Automapper ignore void methods?
问题描述
我是Automapper的新手,所以不确定是否可行.
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.
类型为'AutoMapper.AutoMapperMappingException'的未处理的异常 发生在AutoMapper.dll
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 are using an interface as a destination type AutoMapper will dynamically create an implementation (proxy) type for you.
但是代理代仅支持属性,因此它为您的IgnoreMe
方法抛出了不太描述性的异常.因此,您不能忽略您的IgnoreMe
方法.
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.
作为一种解决方法,您可以使用ConstructUsing
重载之一明确指定应如何构造目标对象,在这种情况下,AutoMapper不会生成代理.
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());
或者,除非没有充分的理由,否则您可以直接映射到Foo
Or unless you have no good reason, you can directly map to Foo
Mapper.CreateMap<IThing, Foo>();
这篇关于Automapper可以忽略void方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!