Reputation: 174
I am trying to transfer the information of a string in an inner class with automapper. How can I get the value of D? My first attempt was:
C = new C { D = "123"}
This failed in dotnetfiddle, so what would be the right approach?
Is it even possible to Map an inner class to another object or is it necessary to change the mapping in order of it to work?
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);
}
}
Upvotes: 2
Views: 2072
Reputation: 236208
There is nothing to map here. You have nested class declaration. It's not data. You should have a field or property of nested class type:
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; }
}
}
Next you need mapping between nested classes:
Mapper.CreateMap<Foo.C,Bar.C>();
And data to map:
var foo = new Foo { A ="test", B = 100500, Value = new Foo.C { D = "foo" }};
Mapping:
var bar = Mapper.Map<Bar>(foo);
After mapping bar
object will have following values:
{
"A": "test",
"B": 100500,
"Value": {
"D": "foo"
}
}
Further reading: Nested Types Best Practice
Upvotes: 2