Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Where does a DBContext class go?

Im working on an MVC 5 project in ASP.NET and have just setup a local DB but im not to sure where the DB context class would fit in with the MVC structure

like image 756
AnonDCX Avatar asked Feb 02 '26 23:02

AnonDCX


1 Answers

Typically I'd separate that out into a separate Whatever.Data project/layer, so that the solution structure would look something like:

enter image description here

The advantage of doing it this way, is that it lets you group together topics that only concern the Data layer. A typical data layer project might look like:

enter image description here

Going a little beyond what you had asked, I personally use the DbContext mainly in a repository, and I inject the repository into the controller with dependency injection.

Each repository method is a special-purpose domain behavior / business rule.

enter image description here

On the other hand, if you're exposing OData, then the ApiController does need the DbContext & Entity Framework et al.

like image 120
RJB Avatar answered Feb 04 '26 15:02

RJB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!