I am trying to implement the service and repository patterns in my ASP.NET Core 6 based web application (using EF Core), but I think I am doing a few things wrong. In my controllers I inject a service instance which I can then use like this to get, create, update or delete entities:
[HttpPost]
public async Task<IActionResult> CreateProject([FromBody] Project body)
{
int projectId = await this.projectService.CreateProjectAsync(body);
return CreatedAtAction(nameof(GetProject), new { id = projectId }, null);
}
The CreateProjectAsync
function then performs validations (if necessary) and calls the corresponding CreateProjectAsync
function of the ProjectRepository
class. One important thing to note is that the Project
class is created by myself and serves as view model, too. It is mapped to the corresponding EF Core type (such as TblProject
) in the repository before it is created/updated in the database or after it has been read from the database.
This approach works fine in many cases but I often encounter problems when I need to use transactions. One example would be that in addition to projects, I also have related entities which I want to create at the same time when creating a new project. I only want this operation to be successful when the project and the related entities were both successfully created, which I cannot do without using transactions. However, my services are not able to create a transaction because they are not aware of the EF Core DbContext
class, so my only option right now is to create the transactions directly in the repository. Doing this would force me to create everything in the same repository, but every example I've seen so far suggests to not mix up different entities in a single repository.
How is this usually done in similar projects? Is there anything wrong with my architecture which I should consider changing to make my life easier with this project?