EntityFramework in the DbContext use suspect description

Source: Internet
Author: User
Tags garbage collection

How can 1.DbContext be used in ASP.MVC?
public class Repository    {        //Instantiate EF container: There are drawbacks. A thread may create multiple DbContext        //dbcontext db = new DbContext ();        Retrofit: Ensure that there is only one copy of the EF container in a request thread (you have to understand: a URL request to the server, IIS opens a thread to process)        protected DbContext getdbcontext        {            get            {                ///to the thread cache, if the return is NULL, it is created and deposited into this thread cache                //note is thread cache CallContext, rather than the httpruntime.cache we are familiar with. This means that the DbContext object is shared by other methods within the thread.                Object efdbcontext = CallContext.GetData ("DbContext");                if (Efdbcontext = = null)                {                    efdbcontext = new DbContext ();                    Deposit into this thread cache                    callcontext.setdata ("DbContext", Efdbcontext);                }                return efdbcontext as DbContext;}}}  

After this definition, all the places that need to use the DbContext object are tuned to this method.

2. Do not casually use or dispose dbcontext will cause lazy loading to be unavailable, there will be some other errors such as iqueryable<t> the following method (. First ()/. Count ()) is also not available. Situation One:

A The result is correct

Phonebookentities phonebookentities = new Phonebookentities (); var ci = PhoneBookEntities.ContactInfo.FirstOrDefault () ;//This does not get the GroupInfo attribute inside the CI object. if (CI! = null) MessageBox.Show (CI. Groupinfo.groupname);//is a deferred load, access to CI. Groupinfo.groupname will go to the database to check the data.

B Error in spelling

ContactInfo ci = null;using (phonebookentities phonebookentities = new Phonebookentities ()) {CI = PhoneBookEntities.ContactInfo.FirstOrDefault ();} if (CI! = null) MessageBox.Show (CI. Groupinfo.groupname);//error: This ObjectContext instance has been released and can no longer be used for operations that require a connection. means that lazy loading is not available.
Situation Two:

A spelling error

Iqueryable<contactinfo> ci = null;using (phonebookentities phonebookentities = new Phonebookentities ()) {CI = PhoneBookEntities.ContactInfo.Where (c = true);} if (CI! = null) MessageBox.Show (CI. Count (). ToString ());//ERROR: Hint DbContext has been released.

b correct wording

Iqueryable<contactinfo> ci = null;using (phonebookentities phonebookentities = new Phonebookentities ()) {CI = PhoneBookEntities.ContactInfo.Where (c = true); if (CI! = null) MessageBox.Show (CI. Count (). ToString ());//can return the correct result. }

  

3. Why do you want the using or Dispose drop dbcontext?

Are you concerned that the database connection is not released? Or are you worried that DbContext is taking up too much resources?
It is certainly unnecessary to worry about the database connection being released first, because DbContext will release the Open database connection when SaveChanges is complete.
You can decompile the source code of Savechages.
It is also unnecessary to worry that DbContext is taking up too much resources and GC recycling.

The conclusion is that youcan call Dispose, but the most common scenarios you don ' t need to.

More details can be seen in this English blog article, which has Diego Vega (the Senior SDE leads on EF) Reply:

Hello Jon,

The default behavior of DbContext is, the underlying connection is automatically opened all time is needed and closed When it is no longer needed. e.g. when you execute a query and iterate through query results using "foreach", the call to Ienumerable<t>. GetEnumerator () would cause the connection to being opened, and when later there is no more results available, "foreach" would Take care of calling Dispose on the enumerator, which would close the connection. In a similar-out, a call to Dbcontext.savechanges () would open the connection before sending changes to the database and WI ll close it before returning.

Given This default behavior, in many Real-world cases it's harmless to leave the context without disposing it and just re Ly on garbage collection.

That said, there is both main reason our sample code tends to always use the "using" or the "dispose" of the context in some and other-a-to:

1. The default automatic open/close behavior is relatively easy-to-override:you can assume control of when the connection is opened and closed by manually opening the connection. Once you start doing this in some part of your code, then forgetting to dipose the context becomes harmful, because MI Ght be leaking open connections.

2. DbContext implements idiposable following the recommended pattern, which includes exposing a virtual protected Dispose Method that derived types can override if for example the need to aggregate other unmanaged resources into the lifetime of The context.

By the same, with DbContext the pattern to open the connection manually and override the automatic open/close behavior are a Bit awkward:

((Iobjectcontextadapter) dbContext). ObjectContext.Connection.Open ()

But we had a bug to make the easier as it used to is with ObjectContext before, e.g.:

DbContext.Database.Connection.Open ()

Hope this helps,

Diego

Attached Reference blog: http://www.cnblogs.com/mecity/archive/2011/07/17/2108508.html

EntityFramework in the DbContext use suspect description

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.