我使用nhibernate将元素从一个对象映射到另一个对象。但是,我的复杂对象中的一个元素需要设置条件,以便目标对象元素相应地设置值。
详细解释
#variables
doc = '/lab01/Projects/Lords_Projects/mna_exons.csv'
save = '/lab01/Projects/Lords_Projects/mna_exac.csv'
other = '/lab01/Projects/Lords_Projects/mna_alt.csv'
error = '/lab01/Projects/Lords_Projects/mna_error.csv'
seek = 'ExAC_ALL'
comp = .05
#script
import csv
#open
read = open(doc, 'rb')
write = open(save, 'wb')
dif = open(other, 'wb')
mis = open(error, 'wb')
#text conversion
reader = csv.DictReader(read, delimiter=',')
copy = csv.DictWriter(write, delimiter='\t', fieldnames=reader.fieldnames)
alt = csv.DictWriter(dif, delimiter='\t', fieldnames=reader.fieldnames)
er = csv.DictWriter(mis, delimiter='\t', fieldnames=reader.fieldnames)
#headers
head = {}
for n in reader.fieldnames:
head[n] = n
copy.writerow(head)
alt.writerow(head)
er.writerow(head)
#sorting
for row in reader:
try:
if float(row[seek]) < comp and float(row[seek]) > -comp:
copy.writerow(row)
elif float(row[seek]) >= comp or float(row[seek]) <= -comp:
alt.writerow(row)
except:
try:
if row[seek] == 'N/A':
copy.writerow(row)
except:
prob = csv.writer(write, delimiter='\t')
er.writerow(row)
prob.writerow("Value Not Float\n")
#Close
read.close()
write.close()
dif.close()
mis.close()
#Error Check
if 'Value Not Float\n' in open(save, 'r').read():
print('Error')
open(save, 'r').close()
因此,您可以看到我想根据源对象中的值设置目标对象上的嵌套对象,以创建对象并将其保存到目标元素。上面的示例代码我尝试过,但它抛出一个错误,说我不能在lambda表达式上使用字符串。
有谁知道如何根据条件设置对象?
由于
答案 0 :(得分:0)
我认为这对你有用。不幸的是,它基于AutoMapper 6.1.1。希望你能使用这个版本。因为我不知道你的类结构,所以我创建了简单的测试类,但你应该能够将样本传递给你的场景。
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);
测试类和枚举
class OneObject
{
public string value { get; set; }
}
class AnotherObject
{
public object complexelement { get; set; }
}
enum Testenum
{
A,
B,
C
}