Context Dispose should be used in ASP.NET MVC?

1

In Web Forms whenever I mounted some kind of CRUD , I used using to make an implen in>.

public List<Produtos> Lista ()
{
    using (var ctx = new DbContext())
    {
        return ctx. Produtos.ToList();
    }
}

In ASP.NET MVC this is done in what way?

public ActionResult Lista ()
{
    DbContext ctx = new DbContext ();
    return View ( ctx. Produtos );
}
    
asked by anonymous 24.03.2016 / 19:47

2 answers

3

You can even do the same, but it's not necessary. The executed process is ephemeral and there will be release of resources upon completion, this is guaranteed by the framework so the first form is correct.

Note that this occurs only because of the ephemeral nature of its operation. There will be no manual release. If there is any reason to find (there is probably something wrong) that needs to be released first of all if it concludes, then the second form is more interesting. I put this more completely for information. Usually you'll let EF take care of it for you.

Read more and still < a href="http://mehdi.me/ambient-dbcontext-in-ef6/"> here .

    
24.03.2016 / 19:59
3

In MVC you can use this way, which is the way I see the most in CRUD projects

public ActionResult Index()
{
    using (var db = new Contexto())
    {
        return View(db.Produtos.ToList());
    }
}

Remembering that ActionResult can return only View() with no objects.

Although I have projects I have seen that the connection context stays outside the Actions as a controller variable, however it goes of taste and needs of the project.

    
24.03.2016 / 19:54