在 Net6 WebApi 中,使用 EF Core 进行查询后,将结果转化为 DTO 可以通过 AutoMapper 来实现。

首先需要在 NuGet 包管理中安装 AutoMapper 和 AutoMapper.Extensions.Microsoft.DependencyInjection 包。

然后在 Startup.cs 文件中的 ConfigureServices 方法中添加以下代码:

services.AddAutoMapper(typeof(Startup));

然后在需要进行 DTO 转换的方法中,注入 IMapper 接口,并使用 Map 方法进行转换,示例如下:

[HttpGet]
public async Task<ActionResult<IEnumerable<ProductDto>>> GetProducts()
{
    var products = await _context.Products.ToListAsync();
    var productDtos = _mapper.Map<List<ProductDto>>(products);
    return Ok(productDtos);
}

其中,ProductDto 是一个与 Product 实体对应的 DTO 类,示例如下:

public class ProductDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

这样就可以在 Net6 WebApi 中使用 EF Core 进行查询后转换为 DTO 了。

net6 webapi 使用efcore查询后转dto

原文地址: https://www.cveoy.top/t/topic/qf0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录