1

Okay, I feel a bit foolish for having to ask this but I guess my understanding of the inner workings of Entity Framework is lacking.

I'd like to experiment with work with DbContext. I have an existing ASP.NET MVC application using EF 4.2. I can get my entities using:

var context = new MyEntities();

And this works just fine.

But how the heck to I get the same data represented by a DbContext?

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466

1 Answers1

4

So I guess you are using default code generator provided by EDMX designer - it will use ObjectContext and heavy weight EntityObject based entities.

If you want to use DbContext you must:

  • Turn off that default code generation - in property window remove Custom Tool for EDMX file
  • Download and install DbContext T4 generator (you can get it directly from extension manager in Visual Studio)
  • In EF designer select Add Code Generation Item from context menu in the designer surface (not on entity)

Now EF will add two .tt files to your project - one will be responsible for creating a new class for every entity or complex type defined in your EDMX file and the second will be responsible for creating class derived from DbContext and exposing sets for all your entity types

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Based on what I know, this sounds like exactly the right answer. But I'm having trouble getting a deeper understanding of what's happening here. I have an ASP.NET MVC book but I don't like they way they implement the repository. Can you recommend any reading material that would provide a deeper understand of what's happening here under the covers? Thanks. – Jonathan Wood Jun 24 '12 at 20:08
  • 1
    This only takes EDMX file which is actually some complex XML and use T4 transformation for creating code files (you can even change the transformation because it is part of your project). There is nothing more. It has no relation to repositories and other patterns. It is just simple and customizable generation of your entity and context classes which follows rules required by EF. – Ladislav Mrnka Jun 24 '12 at 20:14