Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of EF 6.x DbContext Generator option when adding a new data item in Visual Studio

I have a web app that I built using LINQ to SQL and I'm looking to upgrade it to LINQ to Entity Framework. I've looked at some tutorials and what I've learned is that basically in the database-first scenario, you create an ADO.NET Entity Data Model. And from there, you select which tables to include in the model (very similar to LINQ to SQL).

Within the Add New Item dialog, I see that there is another option that creates an EF 6.x DbContext Generator:

Visual Studio Add New Item dialog

What is the purpose of EF 6.x DbContext Generator compared to ADO.NET Entity Data Model (first option in dialog)? And, what is EF 6.x DbContext Generator for? It seems to create a text file. What should I do with it?

like image 426
frenchie Avatar asked Apr 01 '14 16:04

frenchie


People also ask

What is EF 6 x DbContext generator?

The EF 6. x DbContext Generator is T4 template which is basically a code generator.

What is the use of DbContext in Entity Framework?

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.

Should I use using in DbContext?

EF and EF Core DbContext types implement IDisposable . As such, best practice programming suggests that you should wrap them in a using() block (or new C# 8 using statement). Unfortunately, doing this, at least in web apps, is generally a bad idea.

What is application DbContext?

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. DbContext in EF Core allows us to perform following tasks: Manage database connection.


1 Answers

The DbContext Generator replaces the ObjectContext with much simpler and shorter code to connect Entity objects to database objects. A single database table with 30 fields is represented by about 800 lines of code as an ObjectContext but about 40 lines of easy to understand code as a DbContext and class generated by the DbContextGenerator.

The DbContext Generator creates two files -

  1. creating the DbContext with connection string details and a DbSet for each table.

  2. creating the class representing each table. If you open these .tt folders you will see the DbContext and classes generated. You don't need to do anything with these classes - you refer to them in the Controller actions.

A walkthrough is available at http://msdn.microsoft.com/en-US/data/jj206878

like image 68
William Smith Avatar answered Sep 17 '22 00:09

William Smith