The MVC3.1 scaffolding that was released at Mix can auto-magically create an EF 4.1 DBContext class, the basic CRUD code in your controller and the relevant views all in one fell swoop. (Don’t forget the additional scaffolding tools that will build things more intelligently, i.e. with a Repository (http://blog.stevensanderson.com/2011/01/13/scaffold-your-aspnet-mvc-3-project-with-the-mvcscaffolding-package/).
All of the demos of this, including my own [MVC 3 and EF 4.1 Code First: Here are my classes, now you do the rest, kthxbai] demonstrate the new scaffolding using Code First. In other words, just provide some classes and the scaffold will do the rest, including build the context class.
I saw a note on twitter from someone asking about using this feature with an EDMX file instead of going the code first way. You can absolutely do that. Here’s a simple demo of how that works and I’m using the in-the-box template in the MVC 3.1 toolkit — though admittedly, for my own purposes, I’m more likely start with the template that creates a repository.
1) Start with a class library project where I’ve created a database first EDMX file.
2) Use the designer’s “Add Code Generation Item” and select the DbContext T4 template included with Entity Framework 4.1. That will add two templates to the project. The first creates a DbContext and the second creates a set of very simple classes – one for each of the entities in your model.
3) Add an ASP.NET MVC3 project to the solution.
4) Add a reference to the project with the model.
5) BUILD THE SOLUTION! This way the Controller wizard will find the classes in the other project.
6) Copy the connection string from the model project’s app.config into the mvc project’s web.config. Step 7 will complain otherwise.
That will create the controller and the views. The controller has all of the super-basic data access code for read/write/update/delete of the class you selected. It’s a start.
Almost ready to run but first a bit of house keeping.
8) The most common step to forget! Modify the global.asax which will look for the Home controller by default. Change it so that the routing looks for your new controller.
9) Time to test out the app. Here’s the home page. I did some editing also. It all just works.
I highly recommend checking out the alternate scaffolding templates available in the mvc3 scaffolding package linked to above.
Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!