Description of the use of DbContext in EntityFramework, entitydbcontext

Source: Internet
Author: User

Description of the use of DbContext in EntityFramework, entitydbcontext
1. How does DbContext be used in Asp. mvc?

Public class Repository {// instantiate EF container: there are drawbacks. Multiple DbContext may be created in one thread // DbContext db = new DbContext (); // Transformation: ensure that there is only one EF container in one request thread (you need to understand: when a url request is sent to the server, IIS opens a thread for processing.) protected DbContext GetDbContext {get {// query the thread cache. If the returned value is null, it is created, stored in this thread cache at the same time // note that the thread caches CallContext, rather than the familiar HttpRuntime. cache. This means that this DbContext object can be shared by other methods in this thread. Object efDbContext = CallContext. getData ("DbContext"); if (efDbContext = null) {efDbContext = new DbContext (); // save it to CallContext in the thread cache. setData ("DbContext", efDbContext) ;}return efDbContext as DbContext ;}}}

After this definition, call this method for all the places where the DbContext object needs to be used.

2. do not use using or Dispose DbContext to cause delayed loading to become unavailable. There will also be some other errors, such as the method below IQueryable <T> (. first ()/. count () cannot be used either. Scenario 1:

A is written correctly.

PhoneBookEntities phoneBookEntities = new PhoneBookEntities (); var ci = phoneBookEntities. ContactInfo. FirstOrDefault (); // The GroupInfo attribute in the ci object is not obtained here. If (ci! = Null) MessageBox. Show (ci. GroupInfo. GroupName); // delayed loading. Access ci. GroupInfo. GroupName to check data in the database.

Error in writing B

ContactInfo ci = null; using (PhoneBookEntities phoneBookEntities = new PhoneBookEntities () {ci = phoneBookEntities. ContactInfo. FirstOrDefault ();} if (ci! = Null) MessageBox. Show (ci. GroupInfo. GroupName); // error: the ObjectContext instance has been released and cannot be used for operations requiring connection. This means that the delayed loading is unavailable.
Scenario 2:

A writing 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: DbContext has been released.

B written correctly

IQueryable <ContactInfo> ci = null; using (PhoneBookEntities phoneBookEntities = new PhoneBookEntities () {ci = phoneBookEntities. ContactInfo. Where (c => true); if (ci! = Null) MessageBox. Show (ci. Count (). ToString (); // you can return the correct result .}

  

3. Why do you need using or dispose to drop DbContext?

Are you worried that the database connection is not released? Do you still worry that DbContext occupies too many resources?
First, it is unnecessary to worry that the database connection is not released because DbContext releases the opened database connection after SaveChanges is complete.
You can decompile the source code of SaveChages.
We are worried that DbContext occupies too many resources, and GC is used for collection.

Conclusion: You can call Dispose, but in most common scenarios you don't need.

For more details, refer to the article in this English blog, which includes replies from Diego Vega (the Senior SDE Lead on EF:

Hello Jon,

The default behavior of DbContext is that the underlying connection is automatically opened any time is needed and closed when it is no longer needed. E.g. when you execute a query and iterate over query results using “foreach”, the call to IEnumerable<T>.GetEnumerator() will cause the connection to be opened, and when later there are no more results available, “foreach” will take care of calling Dispose on the enumerator, which will close the connection. In a similar way, a call to DbContext.SaveChanges() will open the connection before sending changes to the database and will close it before returning.

Given this default behavior, in many real-world cases it is harmless to leave the context without disposing it and just rely on garbage collection.

That said, there are two main reason our sample code tends to always use “using” or dispose the context in some other way:

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 you might 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 way, with DbContext the pattern to open the connection manually and override the automatic open/close behavior is a bit awkward:

((IObjectContextAdapter)dbContext).ObjectContext.Connection.Open()

But we have a bug to make this easier as it used to be with ObjectContext before, e.g.:

dbContext.Database.Connection.Open()

Hope this helps,

Diego

Add reference blog: http://www.cnblogs.com/mecity/archive/2011/07/17/2108508.html

 

Related Article

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.