繁体   English   中英

实体框架核心、工作单元和存储库模式

[英]Entity Framework Core, Unit of Work and Repository Pattern

在阅读了大量文章后指出不建议将 UOW 和存储库模式放在 EF Core db 上下文之上,我几乎已经加入并即将在我的一个新项目中实现注入 IDBContext 的服务。

我说的差不多,因为我以前使用过一个功能,我不明白如何在没有存储库的情况下实现。

在之前的项目中,我在 EF 之上使用了 UOW 和存储库模式,并从服务中访问它们。 以下方法将位于存储库中,此后可以通过从任何服务调用uow.StudentRepository.Get(id)来调用。

public async Task<Student> Get(Guid id)
    {
        return await _context.Students
            .Include(x => x.Course)
            .Include(x=>x.Address)
            .Include(x => x.Grade)
            .FirstOrDefaultAsync(x => x.Id == id);
    }

如果没有存储库,从 IDBContext 查询,我将不得不调用...

_context.Students
            .Include(x => x.Course)
            .Include(x=>x.Address)
            .Include(x => x.Grade)
            .FirstOrDefaultAsync(x => x.Id == id);

...每次我想做这个查询。 这似乎是错误的,因为它不会是干燥的。

问题

有人可以建议一种方法,我可以在没有存储库的情况下在一个地方声明此代码吗?

听起来你需要一项服务。 你可以创建一个像 DbContext 这样的服务,这样你就可以将它注入到你的控制器中。

IStudentService.cs

public interface IStudentService
{
    Task<List<Student>> GetStudents();
    // Other students methods here..
}

StudentService.cs

public class StudentService : IStudentService
{
    private readonly DataContext _context;

    public StudentService(DataContext context)
    {
        _context = context;
    }

    public async Task<List<Student>> GetStudents()
    {
        return await _context.Students
        .Include(x => x.Course)
        .Include(x=>x.Address)
        .Include(x => x.Grade)
        .ToListAsync();
    }
}

然后将服务注册到Startup.cs中的ConfigureServices()

services.AddScoped<IStudentService, StudentService>();

现在您可以将服务注入任何 controller。 例子:

[ApiController]
[Route("api/[controller]")]
public class StudentController: ControllerBase
{
    private readonly IStudentService _studentService;
    private readonly DataContext _context;

    public StudentService(DataContext context, IStudentService studentService)
    {
        _context = context;
        _studentService = studentService;
    }

    [HttpGet]
    public virtual async Task<IActionResult> List()
    {
        return Ok(await _studentService.GetStudents());
    }
}

确保仅当您将在多个控制器上使用该服务并避免陷入反模式时才创建该服务。

暂无
暂无

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

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