如何简化将实体框架实体转换为DTO

时间:2018-02-19 06:30:26

标签: entity-framework asp.net-web-api asp.net-core

我从ASP.NET Web API中检索项目时映射到数据转换对象,如下所示:

public async Task<IList<PromotionDTO>> GetPromotionsList()
{
    return await _context.Promotions
    .Select(p => new PromotionDTO
    {
        PromotionId = p.PromotionId,
        Is_Active = p.Is_Active,
        Created = p.Created,
        Title = p.Title,
        BusinessName = p.BusinessName,
    })
    .Where(x => x.Is_Active)
    .OrderByDescending(x => x.Created)
    .ToListAsync();
}

就像获得单一记录一样:

public async Task<PromotionDTO> GetPromotion(int id)
{
    return await _context.Promotions
    .Select(p => new PromotionDTO
    {
        PromotionId = p.PromotionId,
        Is_Active = p.Is_Active,
        Created = p.Created,
        Title = p.Title,
        BusinessName = p.BusinessName,
    })
    .Where(x => x.Is_Active && x.PromotionId == id)
    .FirstOrDefaultAsync();
}

我是DTO的新手,我发现我在许多地方都使用相同的DTO转换代码,并且想知道如何简化我的代码才能执行此操作一次?

2 个答案:

答案 0 :(得分:1)

一种选择是创建一个返回IQueryable的方法,然后在每个

中使用它
Private IQueryable<PromotionDTO> Query()
{
    return _context.Promotions
    .Select(p => new PromotionDTO
    {
        PromotionId = p.PromotionId,
        Is_Active = p.Is_Active,
        Created = p.Created,
        Title = p.Title,
        BusinessName = p.BusinessName,
    });
}

public async Task<IList<PromotionDTO>> GetPromotionsList()
{
    return await Query()
    .Where(x => x.Is_Active)
    .OrderByDescending(x => x.Created)
    .ToListAsync();
}

public async Task<PromotionDTO> GetPromotion(int id)
{

    return await Query()
    .Where(x => x.Is_Active && x.PromotionId == id)
    .FirstOrDefaultAsync();
}

答案 1 :(得分:1)

虽然像你所说的那样映射可能就足够了,但是当你的项目开始增长时,它只会使事情变得复杂并导致额外的工作。

我建议你使用像AutoMapper这样的某种映射库。 https://github.com/AutoMapper/AutoMapper

NSLocalizedString