iAteABug_And_iLiked_it
iAteABug_And_iLiked_it

Reputation: 3795

Why use EF 5.X DbContext Generator when Edmx does the same job?

I am finding this EF 5 dbContext tricky to grasp.

In VisualStudio 2012, when I Choose

Project > Add New item > ADO.Net Entity Data Model

and choose the AdventureWorks database file, it generates an edmx file( after asking me to copy the database file locally).

Now that is it, I can now start running queries , e.g.

AdventureWorks_DataEntities entities = new AdventureWorks_DataEntities
var query = from p in entities.Products
            where p.ListPrice >= 0
            select p;

What is confusing me is , why would then I use the

Project > Add New Item > EF 5.X DBcontext Generator

Is it so that I can bind my WPF controls to the database tables? but my query is working, can I not just bind to the edmx objects, after all I can "see" the tables such as Product.cs that have already been mapped.

If that is correct then is it right to say that utilizing EntityFramework is a two step process

Question Part1:

Step 1 : Add a new edmx file generated from the database

Step 2 : Add a new DbContext, which will automatically detect the above edmx file and provide a dbcontext to which one can bind controls, such as datagrids etc.

Question Part2:

I can already see Product.cs in my edmx model having been mapped from the Product table in step1, why can't I bind my WPF controls straight to that , why is step 2 above necessary?

Thank you

Upvotes: 17

Views: 11301

Answers (1)

chuwik
chuwik

Reputation: 867

When you add the new "ADO .NET Entity Data Model", apart from creating the EDMX it also creates the DbContext for you, it's "AdventureWorks_DataEntities".

So, you don't need to add a "EF 5.X DBcontext Generator", this already exists in your project. If in Visual Studio you click on the arrow on the left of your .edmx file to unfold it, you'll see several files. Two of them will end in ".tt". These are T4 templates, which are in charge of generating the model entities and the DbContext automatically when you modify the EDMX.

Hope this clarifies the concepts, to answer your questions directly:

Question 1: You only need step 1, "AdventureWorks_DataEntities" is your DbContext. If you open the "AdventureWorks_DataEntities.cs" file you'll see this class inherits from DbContext.

Question 2: This is a different question, you should open a separate one asking how to bind WPF with Entity Framework. Before you do this, I'd suggest you search online first as there are plenty of resources explaining this. For instance, this MSDN article: http://msdn.microsoft.com/en-us/data/jj574514.aspx

Upvotes: 17

Related Questions