我试图将输入的对象映射到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
以某种方式处理这个吗?
答案 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"