Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 4.0 自动映射:映射匿名/动态类型_C# 4.0_Automapper 5 - Fatal编程技术网

C# 4.0 自动映射:映射匿名/动态类型

C# 4.0 自动映射:映射匿名/动态类型,c#-4.0,automapper-5,C# 4.0,Automapper 5,我需要一些帮助来使用Automapper映射匿名对象。目标是在ProductDto中结合产品和统一(其中统一是产品的属性) AutommaperCreateMissingTypeMaps配置设置为true 我的班级: public class Product { public int Id { get; set; } } public class Unity { public int Id { get; set; } } public class ProductDto

我需要一些帮助来使用Automapper映射匿名对象。目标是在ProductDto中结合产品和统一(其中统一是产品的属性)

Autommaper
CreateMissingTypeMaps
配置设置为
true

我的班级:

public class Product 
{
    public int Id { get; set; }
}

public class Unity 
{
    public int Id { get; set; }
}

public class ProductDto 
{
    public int Id { get; set; }
    public UnityDto Unity{ get; set; }
}

public class UnityDto
{
    public int Id { get; set; }
}
测试代码

Product p = new Product() { Id = 1 };
Unity u = new Unity() { Id = 999 };
var a = new { Product = p, Unity = u };

var t1 = Mapper.Map<ProductDto>(a.Product); 
var t2 = Mapper.Map<UnityDto>(a.Unity);
var t3 = Mapper.Map<ProductDto>(a); 

Console.WriteLine(string.Format("ProductId: {0}", t1.Id)); // Print 1
Console.WriteLine(string.Format("UnityId: {0}", t2.Id)); // Print 999
Console.WriteLine(string.Format("Anonymous ProductId: {0}", t3.Id)); // Print 0 <<< ERROR: It should be 1 >>>
Console.WriteLine(string.Format("Anonymous UnityId: {0}", t3.Unity.Id)); // Print 999
productp=newproduct(){Id=1};
Unity u=new Unity(){Id=999};
VarA=new{Product=p,Unity=u};
var t1=Mapper.Map(a.Product);
var t2=Mapper.Map(a.Unity);
var t3=映射器.Map(a);
Console.WriteLine(string.Format(“ProductId:{0}”,t1.Id));//打印1
Console.WriteLine(string.Format(“UnityId:{0}”,t2.Id));//打印999
Console.WriteLine(string.Format(“匿名ProductId:{0}”,t3.Id));//打印0>
Console.WriteLine(string.Format(“匿名UnityId:{0}”,t3.Unity.Id));//打印999
配置文件中添加了两个地图:

CreateMap<Product, ProductDto>();
CreateMap<Unity, UnityDto>();
CreateMap();
CreateMap();

问题在于Automapper如何映射匿名对象。我没有时间查看Automapper源代码,但我在匿名对象上做了一些小改动,获得了所需的行为:

var a = new { Id = p.Id, Unity = u };
通过这样做,我甚至可以删除以前的映射,因为现在它只使用
CreateMissingTypeMaps


注意:事实上,我不确定这是否真的是一个问题,或者这只是我不真实的期望。

这个答案说在调用
Map
::时传递设置,但这是已知的类型。CreateMissingTypeMaps已经工作了。