简体   繁体   English

如何在自动映射器中映射内部类

[英]How to map inner classes in automapper

I am trying to transfer the information of a string in an inner class with automapper. 我正在尝试使用automapper在内部类中传输字符串的信息。 How can I get the value of D? 如何获得D的值? My first attempt was: 我的第一次尝试是:

C = new C { D = "123"}

This failed in dotnetfiddle, so what would be the right approach? 这在dotnetfiddle中失败了,那么正确的方法是什么?

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);
    }
}

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: 映射后的bar对象将具有以下值:

{
  "A": "test",
  "B": 100500,
  "Value": {
    "D": "foo"
  }
}

Further reading: Nested Types Best Practice 进一步阅读: 嵌套类型最佳实践

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM