我正在尝试使用automapper传输内部类中字符串的信息。我怎样才能得到D的值? 我的第一次尝试是:
C = new C { D = "123"}
这在dotnetfiddle中失败了,那么什么是正确的方法呢?
是否可以将内部类映射到另一个对象,或者是否有必要按顺序更改映射?
using System;
using AutoMapper;
public class Foo
{
public string A { get; set; }
public int B { get; set; }
public class C
{
public string D {get;set;}
}
}
public class Bar
{
public string A { get; set; }
public int B { get; set; }
public class C
{
public string D {get;set;}
}
}
public class Program
{
public static void Main()
{
Mapper.CreateMap<Foo,Bar>();
var foo = new Foo { A="test", B=100500}; //how to get c/d?
var bar = Mapper.Map<Bar>(foo);
Console.WriteLine("foo type is {0}", foo.GetType());
Console.WriteLine("bar type is {0}", bar.GetType());
Console.WriteLine("foo.A={0} foo.B={1}", foo.A, foo.B);
Console.WriteLine("bar.A={0} bar.B={1}", bar.A, bar.B);
}
}
答案 0 :(得分:2)
此处无需绘制任何内容。您有嵌套类声明。这不是数据。您应该具有嵌套类类型的字段或属性:
public class Foo
{
public string A { get; set; }
public int B { get; set; }
public C Value { get; set; } // add same to Bar class
public class C
{
public string D { get; set; }
}
}
接下来,您需要在嵌套类之间进行映射:
Mapper.CreateMap<Foo.C,Bar.C>();
要映射的数据:
var foo = new Foo { A ="test", B = 100500, Value = new Foo.C { D = "foo" }};
映射:
var bar = Mapper.Map<Bar>(foo);
映射bar
对象后将具有以下值:
{
"A": "test",
"B": 100500,
"Value": {
"D": "foo"
}
}