Home > Net >  Where do I place the entity framework queries in layered architecture?
Where do I place the entity framework queries in layered architecture?

Time:04-02

I have .net core api project with following folders:

Models contains the database table classes and dbcontext

Services contain logic to send email, and business logic (example calculate student grade based on marks)

Controller contains the controllers with respective actions (api endpoints). The dbcontext is injected into the controller and the endpoints contain the LINQ queries (example: _ctx.Students.Where.....)

I want to organize this into layered architecture.

UI layer will contain the api project (controllers) and reference the business layer dll.

Business layer will contain the send email logic, and business logic (grading based on marks). I think this must reference the data layer to be able to fetch data.

Data layer will contain the table classes and db context.

Where do I place my entity framework queries which were previously in the controller action method?

CodePudding user response:

I usually recommend people to use the repository pattern to structure Asp.net application in a monolithic fashion. At a high level, there are usually three-layer

  1. Repository/Data Layer
  2. Service/Business layer
  3. Controller/API (Web Project)

In Repository Layer, we define all our models and database call(Your Entity framework will be here).

In the Service Layer, We perform all the business logic.

And in the web project, we define all the API endpoints and other client-side interaction services.

The followings are some of the articles related to the Repository pattern:

  1. https://www.linkedin.com/pulse/repository-pattern-c-pawan-verma/
  2. https://medium.com/net-core/repository-pattern-implementation-in-asp-net-core-21e01c6664d7
  3. https://codewithmukesh.com/blog/repository-pattern-in-aspnet-core/

Some articles, here use the same project to define all the layers but you can simply separate all layers into a separate project (class library).

CodePudding user response:

I usually layer my application like this:

  • APIs - EndPoints
  • Application Layer - All glueing code, mapping, orchestra code, utilities, and other application-level code comes here
  • Domain Layer - Purely contains domains, sub-domains, validations, interfaces for repositories and unit of work, and commands.
  • Data Layer - This layer contains the implementation of all the repositories and unit of work interfaces. And this is the layer where I keep all my queries and database-specific code.
  • Related