LINQ to Entities Entity Initialization

By : tghw
Source: Stackoverflow.com
Question!

In the tutorials for ASP.Net MVC, the LINQ to Entities code looks like:

public class MyController : Controller
{
    private Models db;

    public ActionResult Index()
    {
        db = new Models();
        var foo = (from f in db.foo select f).ToList();
        return View(foo);
    }
}

I'm guessing this has something to do with thread safety/connection pooling, but I just wanted to know if anyone knew of any good reasons not to do it this way:

public class MyController : Controller
{
    private readonly Models db = new Models();

    public ActionResult Index()
    {
        var foo = (from f in db.foo select f).ToList();
        return View(foo);
    }
}
By : tghw


Answers

I just put together a tip that covers this in quite a lot of detail.

Your educated guess of threading is just one of the many reasons why it is generally better to construct/dispose of the Context in the method that needs it.

There are some situations where this rule of thumb doesn't hold but they are pretty rare.

See this: Tip 18 - How to decide on a lifetime for your ObjectContext



It could also be that the offending library was built with a different "Platform Toolset" setting (in Project Properties->General).



Two ways:

1.Update to Sp1 to build the lib

2.Please check your build to make sure that Whole Program Optimization is disabled. For a static lib project, go to the property page and change “Configuration Properties->C/C++->Optimization->Whole Program Optimization” to “No”.

By : Gank


This video can help you solving your question :)
By: admin