从Typed对象映射到动态

时间:2014-09-08 13:37:39

标签: asp.net-mvc dynamic mapping automapper

我试图将输入的对象映射到dynamic,但这似乎是不可能的。

例如:

public class Customer
{
    public string CustomerName {get; set;}
    public Category Category {get; set;} 
}

public class Category
{
    public string CategoryName {get; set;}
    public int IgnoreProp {get; set;}
}

然后我希望我的结果如下:

var customer = new Customer
         { 
             CustomerName = "Ibrahim", 
             Category = new Category
                 { 
                   CategoryName = "Human", 
                   IgnoreProp = 10 
                 } 
         };

dynamic dynamicCustomer = Mapper.Map<Customer, dynamic>(customer);

我可以配置AutoMapper以某种方式处理这个吗?

2 个答案:

答案 0 :(得分:1)

看起来有可能,以下测试成功:

public class SourceObject
{
    public int IntProperty { get; set; }
    public string StringProperty { get; set; }
    public SourceObject SourceProperty { get; set; }
}

internal class Program
{
    private static void Main(string[] args)
    {
        var result = AutoMapper.Mapper.Map<dynamic>(new SourceObject() {IntProperty = 123, StringProperty = "abc", SourceProperty = new SourceObject()});
        Console.WriteLine("Int " + result.IntProperty);
        Console.WriteLine("String " + result.StringProperty);
        Console.WriteLine("Object is " + (result.SourceProperty == null ? "null" : "not null").ToString());
        Console.ReadLine();
    }
}

这将使用SourceObject

中的映射属性输出动态对象

答案 1 :(得分:0)

您无需使用AutoMapper映射到动态对象:

dynamic dynamicCustomer = customer;
Console.WriteLine(dynamicCustomer.CustomerName); // "Ibrahim"
Console.WriteLine(dynamicCustomer.Category.CategoryName); // "Human"