繁体   English   中英

从集合项目到字典

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM