I working on .NET CORE 6 application. I have Dictionary<int, string>
that I need to convert to an ICollection of class object. I have create separate profile class; refer below. However I am getting error.
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)))
;
}
}
Calling from class to covert dictionary data...
var ff = _ambientState.Mapper.Map<ICollection<AIMConfigProfile>>(filteredStructuredData);
From what I understand you have a dictionary with specific entries containing the machine code and transaction date(and by your example you know the keys which correspond to these). Here's one way to do it.
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("--------------------");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.