AutoMapper自定义映射 [英] AutoMapper Custom Mappings
本文介绍了AutoMapper自定义映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下课程
public class foo
{
public string Value;
}
public class bar
{
public string Value1;
public string Value2;
}
现在,我想配置自动映射,如果Value1以"A"开头,则将Value1映射到Value,否则,我想将Value2映射到Value.
Now I want to configure Auto Map, to Map Value1 to Value if Value1 starts with "A", but otherwise I want to map Value2 to Value.
这是我到目前为止所拥有的:
This is what I have so far:
Mapper
.CreateMap<foo,bar>()
.ForMember(t => t.Value,
o =>
{
o.Condition(s =>
s.Value1.StartsWith("A"));
o.MapFrom(s => s.Value1);
<<***I want to throw Exception here***>>
})
但是我知道如何有条件地赋予值1或值2,但不知道如何放置一些自定义代码,调用函数或引发异常
However I know how can I give value 1 or value 2 on Conditional basis but don't know how to put some custom code , call a function or throw an Exception
请指导.
推荐答案
您可以将lambda传递给 ResolveUsing
:
You can pass a lambda to ResolveUsing
:
.ForMember(f => f.Value, o => o.ResolveUsing(b =>
{
if (b.Value1.StartsWith("A"))
{
return b.Value1;
}
return b.Value2;
}
));
这篇关于AutoMapper自定义映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文