[英]Convert Dictionary<int, string> to strongly typed class ICollection Using AutoMapper
我正在研究 .NET CORE 6 應用程序。 我有Dictionary<int, string>
,我需要將其轉換為 class object 的 ICollection。我創建了單獨的配置文件 class; 參考下文。 但是我收到錯誤。
Error mapping types.
Mapping types:
List`1 -> ICollection`1
System.Collections.Generic.List`1[[System.Collections.Generic.Dictionary`2[[System.Int32,
System.Private.CoreLib, Version=6.0.0.0, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e],[System.String, System.Private.CoreLib,
Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]],
System.Private.CoreLib, Version=6.0.0.0, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e]]
Entity Class
public class AIMSchema
{
public DateTime TransactionDate { get; set; }
public string MachineCode { get; set; }
}
AutoMapper profile
public class AIMConfigProfile : Profile
{
public AIMConfigProfile()
{
CreateMap<Dictionary<int, string>, AIMSchema>()
.ForMember(dest => dest.TransactionDate, opt => opt.MapFrom(source => source.ContainsKey(1)))
.ForMember(dest => dest.MachineCode, opt => opt.MapFrom(source => source.ContainsKey(2)))
;
}
}
從 class 調用以隱藏字典數據...
var ff = _ambientState.Mapper.Map<ICollection<AIMConfigProfile>>(filteredStructuredData);
據我了解,您有一本字典,其中包含包含機器代碼和交易日期的特定條目(並且通過您的示例,您知道與這些對應的鍵)。 這是一種方法。
IMapper mapper = new MapperConfiguration(opts =>
{
opts.CreateMap<Dictionary<int, string>, AIMSchema>()
.ForMember(x => x.TransactionDate, op => op.PreCondition(x => x.ContainsKey(1)))
.ForMember(x => x.TransactionDate, op => op.MapFrom(x => DateTime.Parse(x[1])))
.ForMember(x => x.MachineCode, op => op.PreCondition(x => x.ContainsKey(2)))
.ForMember(x => x.MachineCode, op => op.MapFrom(x => x[2]));
}).CreateMapper();
List<Dictionary<int, string>> data = new()
{
new()
{
{1, "2022-01-01" },
{2, "code foo" }
},
new()
{
{1, "2022-02-01" },
{2, "code bar" }
},
};
ICollection <AIMSchema> result = mapper.Map<List<Dictionary<int, string>>, List<AIMSchema>>(data);
foreach (var item in result)
{
Console.WriteLine(item.MachineCode);
Console.WriteLine(item.TransactionDate);
Console.WriteLine("--------------------");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.