8
The block using {}
works in the same way in both web applications and desktops in the sense of when we use it in controller
? It is a good practice to declare it in the actions that there is contact with the database
Following are examples, which one would be a good practice?
public class UsuarioController : Controller
{
private EntidadesDCSystem db = new EntidadesDCSystem();
[HttpPost]
public ActionResult Adicionar(Usuario usuario)
{
if (ModelState.IsValid)
{
db.Usuario.Add(usuario);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(usuario);
}
Or:
public class UsuarioController : Controller
{
[HttpPost]
public ActionResult Adicionar(Usuario usuario)
{
using (EntidadesDCSystem db = new EntidadesDCSystem())
{
if (ModelState.IsValid)
{
db.Usuario.Add(usuario);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(usuario);
}
}
It depends a lot. The Controller is usually discarded very quickly because it only exists within the life cycle of the request, so this performance gain is very small.
– Leonel Sanches da Silva
Really Gypsy, this view is valid, yet another important benefit of using is to ensure that the object is used only where it is needed, if you try to use the object outside of using the compiler neither compiles nor generates an error. This prevents someone who has picked up the code from later trying to access it further.
– Julio Borges
Yes, but let’s assume one Controller great, okay? I don’t know, with 15 Actions. You would have to declare the block 15 times. There is not much practical basis. Also, as the
dispose
of Controller does Disposis in everything it implementsIDisposable
, thedispose
of the context will end up happening anyway.– Leonel Sanches da Silva
It makes sense, but the most important thing is to know the concept and apply it in the best way. I can have a controller with 15 actions, but only in a work directly the bank, in this case it would not make sense to instantiate the context and give Dysplasia. Each case is a case, but its answer is more applicable to the concept of the question.
– Julio Borges