Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to use DbContext and not ObjectContext

I am using EF 4.1 & using DB first approach. I have created my .edmx file too. Now i wish to create my POCO classes.

For this, I have installed EF 4.x DbContext Generator as well as EF 4.x POCO Entity Generator from NuGet.

I am fully aware that it is recommnded to use DbContext for EF 4.1+ as it is derived from ObjectContext. However, i still generated my POCO classes by 1st using EF 4.x POCO Entity Generator & then also by EF 4.x DbContext Generator.

EDIT: Found this ADO.NET DbContext Generator vs. ADO.NET Poco Entity Generator (ObjectContext)

In either of the case, it generates .Context.tt & Model.tt files. So what is the exact difference in files generated by either of the tools ? Why is it recommnded to use DbContext for EF 4.1+ ?

I would also like to know limitations of ObjectContext.

like image 937
NoobDeveloper Avatar asked Apr 08 '13 09:04

NoobDeveloper


People also ask

What is the difference between DbContext and ObjectContext?

Dbcontext can be defined as a lightweight version of the ObjectContext or we can say Dbcontext is a wrapper of ObjectContext and exposes only the common features that are really required in programming.

What is the purpose of 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.

What is the difference between DbContext and DbSet?

Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database.


1 Answers

DbContext is newer API which should polish developers experience when using most common tasks - simply the API is better designed but you still have to get ObjectContext from DbContext and use the older API if you want to use some more complex features. If you plan to upgrade EF to 5.x or 6.x in the future it will probably be easier with DbContext because that is what ADO.NET team is recommending.

In terms of generators EF 4.x POCO generator creates more complex classes which internally use relations fix up. This feature proved itself to be quite inefficient when used together with lazy loading so newer EF DbContext generator doesn't use it.

Side note: The code transition from one API to another is fully supported:

  • You can use DbContext constructor accepting ObjectContext to move from ObjectContext API to DbContext API
  • You can use IObjectContext adapter to move from DbContext API to ObjectContext API
like image 187
Ladislav Mrnka Avatar answered Sep 28 '22 15:09

Ladislav Mrnka