Saturday, December 21, 2013

DbContext in Entity Framework

Entity Framework, commonly known as EF (latest being EF Core) is a ORM tool which is introduced and maintained by Microsoft.

In EF, DbContext Is the primary class which is used to interact with data as objects. DbContext is often referred to as context. The context class manages entity objects during run time, which includes populating data from database, change tracking and persisting data back to database.  

What exactly is DbContext class?

DbContext is actually a simplified alternative to ObjectContext. Its like a wrapper over ObjectContext. DbContext is the preferred way to interact with Entity Framework. (Is DbContext same as DataContext?). You can get ObjectContext from DbContext using the following code.


DbContext is most commonly used with derived type that contains DbSet<Entity> properties for the root entities of the model. These sets are automatically initialized when a derived type of DbContext is created. You can override protected method OnModelCreating to modify these models. (See Code First Building Blocks).

What is DbSet?

DbSet represents a table or a view in the database. DbSet(TEntity) cannot be constructed publicly. It can be instantiated only through DbContext instance. See DbSet and DbContext. You will be using DbSet to access, insert, update or delete your table data.

Lifetime of DbContext starts when object is created and ends when the object is disposed or garbage collected. By default context manages connections to the database. The context opens and closes connections as necessary. 

DbContext is not thread safe.You can still create multi-threaded applications as long as instance of same DbContext class is not tracked by multiple contexts at the same time. 

Here's some insight of DbContext class. You can find the source code in codeplex.

DbModelBuilder
Used to map CLR classes to database schema. This is mainly used in Code First approach. MSDN


Timeout in Entity Framework
Entity Framework operations have timeouts. The timeout duration is defined by underlying connection providers. You can set the connection timeout in Entity Framework connection string but there is a known bug in MySQL. Therefore you can set timeout in data context.

this.context.Database.CommandTimeout = 180; 


Overridable members in DbContext

Dispose : Usually you don't need to do this. see this article
SaveChanges and SaveChangesAsync : EF6 onwards 
ValidateEntity and ShouldValidateEntity : see this 


Change Tracking POCO entities

In EF, you can track POCO entity changes through change-tracking proxy object or through a snapshot.

When change tracking with proxies, tracking changes in object graph is automatically done by EF. You can disable proxy creation this using below command. Beware that even if proxy creation is enabled, EF will create proxy classes only if the requirements for proxy creation is satisfied.

entities.Configuration.ProxyCreationEnabled = false;

Proxies are created for lazy loading as well. Not only for change tracking

http://stackoverflow.com/questions/7111109/should-i-enable-or-disable-dynamic-proxies-with-entity-framework-4-1-and-mvc3
https://msdn.microsoft.com/en-us/library/vstudio/dd456848(v=vs.100).aspx
https://msdn.microsoft.com/en-us/library/vstudio/dd456848(v=vs.100).aspx
http://stackoverflow.com/questions/26355486/entity-framework-6-audit-track-changes
http://www.entityframeworktutorial.net/change-tracking-in-entity-framework.aspx
http://www.c-sharpcorner.com/UploadFile/ff2f08/working-with-change-tracking-proxy-in-entity-framework-6-0/

Attaching and Detaching Entities

Objects that are attached to ObjectContext can be tracked and managed by ObjectContext. When your object is detached, it won't be tracked by the object context. By default if you execute a query inside a ObjectContext, entities are attached to object context. 

You can detach entities by one of the options below,

Using MergeOption.NoTracking enumeration or AsNoTracking
See examples here, here and here. Also beware about possible performance issues as mentioned here and here. See advantages of using AsNoTracking here and here.

ObjectContext.Detach method
This method removes the object from ObjectStateManager. Disables change tracking and identity resolution. See the example below,

https://msdn.microsoft.com/en-us/library/vstudio/bb896271(v=vs.100).aspx
http://stackoverflow.com/questions/4168073/entity-framework-code-first-no-detach-method-on-dbcontext

See Working with DbContext (MSDN)
See example files used in this article in this gist

2 comments:

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook