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

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

我几乎说了,因为我以前使用的一个功能是我不了解没有存储库的情况。

在以前的项目中,我在EF上使用了UOW和存储库模式,并从Service中访问了它们。以下方法将在存储库中,此后可以通过从任何服务调用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);

...每次我都想执行此查询。这似乎是错误的,因为它不会是DRY。

问题

有人可以提出一种无需存储库就可以在一个地方声明此代码的方法吗?

smithhyj 回答:实体框架核心,工作单元和存储库模式

听起来像您需要服务。您可以创建像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();
    }
}

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

services.AddScoped<IStudentService,StudentService>();

现在您可以将服务注入到任何控制器中。示例:

[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());
    }
}

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

本文链接:https://www.f2er.com/3063133.html

大家都在问