使用Automapper处理EF导航属性

5
我正在尝试使用EF的导航属性来映射两个集合。
Collection.Items是一个List。
CollectionDTO有一个导航属性指向一个交叉连接表CollectionItem,该表又有另一个导航属性指向Item。
我希望每个CollectionDTO.CollectionItem.Item都能映射到Collection.Item。
我尝试过这个方法但无法解决问题。
有人可以帮忙吗?
var mapperConfig = new MapperConfiguration(cfg =>
{
    // CreateMap<source, destination>()    
    cfg.CreateMap<Collection, CollectionDTO>()
        .ForMember(dest => dest.Items,
                   opts => opts.MapFrom(src =>
                       src.CollectionItems.Where(x => x.CollectionId == src.Id).ToList().ForEach(ci => ci.Item)));

});
1个回答

2
您可以像这样使用“Select”扩展方法:

Select扩展方法的使用方法如下:

// CreateMap<source, destination>()    
    cfg.CreateMap<Collection, CollectionDTO>()
       .ForMember(dest => dest.Items,
                   opts => opts.MapFrom(src =>
                       src.CollectionItems.Select(ci=>ci.Item).ToList()));

如果 Item 导航属性是一个集合,那么请使用 SelectMany 扩展方法:
// CreateMap<source, destination>()    
    cfg.CreateMap<Collection, CollectionDTO>()
       .ForMember(dest => dest.Items,
                   opts => opts.MapFrom(src =>
                       src.CollectionItems.SelectMany(ci=>ci.Item).ToList()));

第二个选项给了我编译错误,但第一个选项运行得非常好!谢谢! - duyn9uyen
不客气 ;). 我猜 CollectionItems 表示连接表,而 Item 是一个引用导航属性。 - ocuenca

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接