Search code examples
asp.net-mvcarchitectureabstraction

Is accessing database directly in the controller an antipattern?


Is:

public ActionResult Whatever(int id) `
{
  using (var db = new Context()) 
  {
     var result = db.Whatevers.Where(x => x.Id == id);
     // ....
  }
}

bad approach and I should lean towards adding layer of abstraction like some kind of Repository (f.e. implementing an interface)?

Something like:

var repo = new MyRepository(db) // context created earlier
var result = repo.GetWhatever(id);

Is there some general rule that I'm missing? Or does it depend on the complexity of the logic inside of the controller. Thanks in advance.


Solution

  • Yes, it is generally a good practice to abstract your database interactions into a separate layer. It is also good practice to always access the resources via an Interface and using dependency inject to resolve the instances of those objects at runtime.

    There is no hard and fast rule on this but in professional environments no one is going to be creating an application with data access logic in their controller.