Unique within the thread created by the EF context object

Source: Internet
Author: User
Tags httpcontext

In a single request, that is, within a thread, if you use the EF data context object to create one, it will cause data confusion, each time the object created by the corresponding database operation, while the other EF objects obtained in the data may already be "expired". That this data has been changed. This is the data chaos, in order to solve this problem, the key is the object creation problem.

The first thing to think about is a singleton pattern, but here, it's not a good idea, because using a singleton mode will cause the EF object to not be released in a timely manner.

The second way is to ensure that the object within the thread is unique, how to ensure that, through the Microsoft ASP mechanism of the HttpContext object, the object is unique in the thread, so we create in the HttpContext or say add an object, Add the EF data context object that we want to create to HttpContext.

How to add it, you can add this method to the tool class (Common.cs) to create a

 if  (Httpcontext.current.item[ "" Span style= "color: #800000;" >db  ] = = null   = // modelcontainer the name of the EF context object that was created, model is the name of the entity model, and its own named  Httpcontext.currentitems[  "] = DB1;  // EF data context object added to HttpContext  Span style= "color: #000000;" >}  else  { //  Description has been added to HttpContext } 

Unique within the thread created by the EF context object

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.