[英]C# Automapper conditional mapping
I am using nhibernate to map elements from one object to another. 我正在使用nhibernate将元素从一个对象映射到另一个对象。 However, one of the elements in my complex objects, needs to have a condition set in order for the destination object element to have a value set accordingly. 但是,我的复杂对象中的元素之一需要设置一个条件,以便目标对象元素具有相应的值。
To explain in detail 详细解释
Mapper.CreateMap<OneObject, AnotherObject>()
.ForMember(
destination => destination.complexelement,
option => option.MapFrom(source=> source.value == enumValue.ToString()
? new object( {Id 123 })
: new object ({ Id 567 }))
So, you can see that I want to set a nested object on the destination object based upon a value from the source object to create an object and save it to the destination element. 因此,您可以看到我想基于源对象中的值在目标对象上设置一个嵌套对象,以创建一个对象并将其保存到目标元素。 The example code above I have tried, but it is throwing an error saying I can't use a string on a lambda expression. 我已经尝试了上面的示例代码,但是它抛出一个错误,说我不能在lambda表达式上使用字符串。
Does anyone know how I can set an object based upon a condition? 有谁知道我如何根据条件设置对象?
Thanks 谢谢
I think this will work for you. 我认为这对您有用。 Unfortunately it is based on AutoMapper 6.1.1. 不幸的是,它基于AutoMapper 6.1.1。 Hope you can use this version. 希望您可以使用此版本。 Because I didn't know your class structure, I created simple test classes, but you should be abled to transfer the sample to your scenario. 因为我不知道您的类结构,所以我创建了简单的测试类,但是您应该能够将样本转移到您的方案中。
OneObject oo = new OneObject();
oo.value = "B";
Testenum enumValue = Testenum.A;
Mapper.Initialize(a => a.CreateMap<OneObject, AnotherObject>()
.ForMember(
destination => destination.complexelement,
option => option.MapFrom(source => source.value == enumValue.ToString()
? 123
: 567)));
AnotherObject ao = Mapper.Map<OneObject, AnotherObject>(oo);
Test classes and enum 测试类和枚举
class OneObject
{
public string value { get; set; }
}
class AnotherObject
{
public object complexelement { get; set; }
}
enum Testenum
{
A,
B,
C
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.