简体   繁体   English

DTO的地图组件也属于DTO

[英]Map components of DTO which are DTOs as well

This is my class which holds database data: 这是我的类,其中包含数据库数据:

public partial class PermissionGroup
{
    public int Id { get; set; }
    public string Name { get; set; }
    // other database properties

    public virtual ICollection<GroupActionPermission> GroupActionPermissions { get; set; }
}

And that's my dto's: 那就是我的dto:

public class PermissionGroupDTO
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<GroupActionPermissionDTO> ActionPermissions { get; set; }
}

public class GroupActionPermissionDTO
{
    public int Id { get; set; }
    public int GroupId { get; set; }
    public int PermissionActionId { get; set; }

    public PermissionGroupDTO Group { get; set; }
}

Now, I am making mapping: 现在,我正在进行映射:

public IEnumerable<PermissionGroupDTO> GetGroups()
{
    return OnConnect<IEnumerable<PermissionGroupDTO>>(db =>
    {
        return db.PermissionGroups
        .Include(i => i.GroupActionPermissions)
        .ProjectTo<PermissionGroupDTO>()
        .ToList();
    });
}

And I am getting collection of PermissionGroupDTO which should contains collection of GroupActionPermissionDTO , but that collection stays null . 而且我正在获取PermissionGroupDTO集合,该集合应包含GroupActionPermissionDTO集合,但该集合保持为null Is there something wrong with my code? 我的代码有问题吗? I am afraid that automapper can map collections from foreign keys. 恐怕automapper会映射外键中的集合。

Also, thats my automapper initializer: 另外,这就是我的自动映射器初始化程序:

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<PermissionGroup, PermissionGroupDTO>();
    cfg.CreateMap<GroupActionPermission, GroupActionPermissionDTO>();
});

I believe the reason is desribed here http://docs.automapper.org/en/stable/Queryable-Extensions.html 我相信这里描述的原因是http://docs.automapper.org/en/stable/Queryable-Extensions.html

Note that for this feature to work, all type conversions must be explicitly handled in your Mapping. 请注意,要使此功能起作用,必须在您的映射中显式处理所有类型转换。

So that means you should manually configure the mapping: 因此,这意味着您应该手动配置映射:

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<PermissionGroup, PermissionGroupDTO>()
       .ForMember(dto => dto.ActionPermissions , conf => conf.MapFrom(ol => ol.GroupActionPermissions )));;
    cfg.CreateMap<GroupActionPermission, GroupActionPermissionDTO>();
});

BTW, note that fields are named differently: GroupActionPermissions vs. ActionPermissions . 顺便说一句,请注意字段的名称不同: GroupActionPermissionsActionPermissions This is also the reason why automapper doesn't map it automatically and then you should use the manual configuration I wrote. 这也是automapper无法自动映射它的原因,然后您应该使用我编写的手动配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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