Retrieve data in controller using context or creation method?

Which of the following is correct, or at least best:

Create a method to retrieve data in the controller:

public ActionResult Index() { var list = _context.MyClass.Take(10); return View(list); } 

or use context directly:

 public ActionResult Index() { var list = MyClass.MethodWrapperToGet(10); return View(list); } 

My concern for the first is that the database is too exposed; making it too easy for developers to abuse it.

+4
source share
2 answers

It depends on the size of your project. For something small or quick prototype, I would go with the option when the controllers directly access the DbContext .

 public ActionResult Index() { var list = _context.MyClass.Take(10); return View(list); } 

I personally prefer to separate the concerts. In other words, I would create a class of service that passes exactly the data that it needs to the controller. Remember that the controller does not need to know how to perform tasks , but instead what needs to be done after that .

This, of course, does not mean that you need to implement a repository template. Your service class can access DbContext directly if you want.

0
source

Ideally, you use the _context exposure option, where you can pass this context through Injection Dependency so that you can Unit Test your controller.

Static calls are very difficult to verify, at least in .Net

0
source

All Articles