[英]Project from a collection to a dictionary
我正在嘗試使用 AutoMapper 將實體上的集合轉換為字典。 這在我使用 Map function 時有效,但是當我使用可查詢擴展 ProjectTo 時它拋出異常。
我在下面創建了一個可重現的示例(通常 ProjectTo 將應用於 EF Core 可查詢對象,但在本示例中,我剛剛從列表中創建了 Queryable - 結果異常是相同的)。
using AutoMapper;
using AutoMapper.QueryableExtensions;
var cfg = new MapperConfiguration(config =>
{
config.CreateMap<ParentItem, ParentItemDTO>()
.ForMember(d => d.ChildItems,
o => o.MapFrom(src => src.ChildItems.ToDictionary(key => key.ChildId, value => value)));
config.CreateMap<ChildItem, ChildItemDTO>();
// I have tried adding this and it does not resolve it - throws a different exception
//config.CreateMap<KeyValuePair<string, ChildItem>, KeyValuePair<string, ChildItemDTO>>();
});
var mapper = new Mapper(cfg);
var parent = new ParentItem
{
ParentId = "1",
ChildItems = new List<ChildItem>() {
new ChildItem() { ChildId = "1", Name = "Child 1" },
new ChildItem() { ChildId = "2", Name = "Child 2" }
}
};
var singleResult = mapper.Map<ParentItem, ParentItemDTO>(parent);
var parentQueryable = (new List<ParentItem>() { parent }).AsQueryable();
// This line fails
var projectionResult = parentQueryable.ProjectTo<ParentItemDTO>(mapper.ConfigurationProvider);
public class ParentItem
{
public string ParentId { get; set; }
public List<ChildItem> ChildItems { get; set; }
}
public class ChildItem
{
public string ChildId { get; set; }
public string Name { get; set; }
}
public class ParentItemDTO
{
public string ParentId { get; set; }
public Dictionary<string, ChildItemDTO> ChildItems { get; set; }
}
public class ChildItemDTO
{
public string ChildId { get; set; }
public string Name { get; set; }
}
這對單個結果成功起作用,但是當它到達 ProjectTo 行時,它會拋出以下異常:
System.InvalidOperationException
HResult=0x80131509
Message=Missing map from System.Collections.Generic.KeyValuePair`2[System.String,ChildItem] to System.Collections.Generic.KeyValuePair`2[System.String,ChildItemDTO]. Create using CreateMap<KeyValuePair`2, KeyValuePair`2>.
我嘗試添加一個 KeyValuePair 映射(在上面的代碼中注釋掉),但它只會拋出一個不同的異常:
System.ArgumentException: 'Argument types do not match'
有誰知道是否可以像這樣使用 ProjectTo 到 map 從集合成員到字典成員? 我的方法有問題嗎,或者這是 AutoMapper 的錯誤/限制?
我正在使用 AutoMapper 11.0.1 和 .Net 6。
CreateMap<ChildItem, KeyValuePair<string, ChildItemDTO>>.ConvertUsing(c => new KeyValuePair<string, ChildItemDTO>(c.ChildId, new ChildItemDTO() { ChildId = c.ChildId, Name = c.Description }))
適用於 MyGet 構建。 對於您的版本,請嘗試 map 到Dictionary
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.