Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is DbContext the same as DataContext?

I'm following a tutorial by Scott Gu that refers to a class named DbContext. I can't find it on any namespace on framework 4 and it seems to me it was renamed from CT4 DbContext to .net4 System.Data.Linq.DataContext. Is my assumption correct?

like image 529
Padu Merloti Avatar asked Aug 12 '10 19:08

Padu Merloti


People also ask

What is DataContext?

The DataContext is the source of all entities mapped over a database connection. It tracks changes that you made to all retrieved entities and maintains an "identity cache" that guarantees that entities retrieved more than one time are represented by using the same object instance.

What is the DbContext?

A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.

Is DbContext part of Entity Framework?

The DbContext class is an integral part of Entity Framework. An instance of DbContext represents a session with the database which can be used to query and save instances of your entities to a database. DbContext is a combination of the Unit Of Work and Repository patterns.

Is DbSet part of DbContext?

The DbSet class represents an entity set that can be used for create, read, update, and delete operations. The context class (derived from DbContext ) must include the DbSet type properties for the entities which map to database tables and views.


2 Answers

DbContext is a new class that was added in the recent separate download by EF team. It is currently not part of the core EF 4.0. However DbContext moving forward would be the preferred way to interact with EF.

So how is it different from ObjectContext? Well semantically they are exactly same but they reduced lot of extra noise that ObjectContext had. Like exposing a set required more work, for instance:

public ObjectSet<Customer> Customers {     get { return db.CreateObjectSet<Customer>(); } } 

With DbContext you can do:

public DbSet<Customer> Customers { get; set; } 

Basically on the ObjectContext, when you do dot (.), everything is just right there which makes the list pretty huge. What the EF team actually wanted to expose on DbContext are entities which are only specific to your domain and rest of ability of the framework is tucked in under different properties. It just makes the programming experience easier.

This means if you are using ObjectContext right now, with a little bit of code, you can easily move to DbContext.

like image 71
zeeshanhirani Avatar answered Sep 21 '22 15:09

zeeshanhirani


It's a bit too late, but for the googlers. DbContext is used for EF (EntityFramework) and DataContext is used for L2S (LINQ To SQL).

like image 44
Dmitrij Kultasev Avatar answered Sep 18 '22 15:09

Dmitrij Kultasev