在单个变体和列表变体中重用DTO映射

时间:2018-12-29 13:36:42

标签: entity-framework linq orm

我们定期编写这样的扩展方法,这些方法将从数据库对象转换为DTO对象,以供我们系统中的其他地方使用。

如以下示例所示,重复了实际的映射代码。是否可以编写可在这两种方法中使用的可重用选择映射?

    public static async Task<List<Group>> ToCommonListAsync(this IQueryable<DataLayer.Models.Group> entityGroups)
    {
        var groups =
            await entityGroups.Select(
                g =>
                    new Group()
                    {
                        Id = g.Id,
                        AccountId = g.AccountId,
                        Name = g.Name,
                        ParentId = g.ParentId,
                        UserIds = g.GroupUserMappings.Select(d => d.UserId).ToList()
                    }).ToListAsync();

        return groups;
    }

    public static async Task<Group> ToCommonFirstAsync(this IQueryable<DataLayer.Models.Group> entityGroups)
    {
        var group =
            await entityGroups.Select(
                g =>
                    new Group()
                    {
                        Id = g.Id,
                        AccountId = g.AccountId,
                        Name = g.Name,
                        ParentId = g.ParentId,
                        UserIds = g.GroupUserMappings.Select(d => d.UserId).ToList()
                    }).FirstOrDefaultAsync();

        return group;
    }

1 个答案:

答案 0 :(得分:1)

您可以将映射/投影代码移到这样的变量中:

public static class Extensions
{
    private static readonly Expression<Func<DataLayer.Models.Group, Group>> Projection = g => 
        new Group
        {
            Id = g.Id,
            AccountId = g.AccountId,
            Name = g.Name,
            ParentId = g.ParentId,
            UserIds = g.GroupUserMappings.Select(d => d.UserId).ToList()
        };

    public static async Task<List<Group>> ToCommonListAsync(this IQueryable<DataLayer.Models.Group> entityGroups)
    {
        return await entityGroups.Select(Projection).ToListAsync();
    }

    public static async Task<Group> ToCommonFirstAsync(this IQueryable<DataLayer.Models.Group> entityGroups)
    {
        return await entityGroups.Select(Projection).FirstOrDefaultAsync();
    }
}