Use MVC Scaffolding in Database First Scenarios
Steve Sanderson's MVC Scaffolding NuGet package is awesome and goes far beyond the very good scaffolding available from the Add Controller dialog in Visual Studio 2010 (after installing the MVC 3 Tools Update).
But a shortcoming of MVC Scaffolding is that, out of the box, it works only in Code First mode. However, with a little finagling you can get it work in a database first scenario. I'm sure there are several different ways to do this but here is what I did that was pretty easy. This assumes the database schema has already been created using SQL Server.
- Add an ADO.NET Entity Data Model to the Models folder of your ASP.NET MVC 3 application.
- Select Generate from database from wizard and generate the entity model for your database objects.
- Right-click on the .edmx model file and select Add Code Generation Item... from the pop-up menu.
- Under Code tab of dialog, select ADO.NET DbContext Generator. This changes the EF model to use DbContext instead of ObjectContext and creates a DbContext class for the database, by default, with the name databaseEntities. For example, I have a database named BPath. So for this database, EF creates a DBContext class named BPathEntities. This step is key because it will make the database-first classes you generate compatible with the code-first classes that MVC Scaffolding generates later.
- Now use MVC Scaffolding to generate the controllers for your app utilizing the entity classes that the DbContext generator generated for you in step #4, which, by default, will have the same name as the tables/views from your database that you selected in step #2.
For example, in my database I have a table named Participant so I would enter
Scaffold Controller Participant -force -repository
into the Package Manager Console to scaffold a controller and views for the Participant entity from the model. The -force option overwrites any existing items and -repository creates repository classes for the entity. - Now open the repository class that MVC Scaffolding created. It will be named, by default entityRepository. So in my example, I would open ParticipantRepository in the code editor in Visual Studio.
- Now you will note that MVC Scaffolding created a different DbContext for itself named, by default, projectnameContext that it references in the ParticipantRepository class.
- Change the context statement so it now uses instead your db-first context instead of MVC scaffolding's code-first context.
In my example, I have commented out the code-first context named BPathMVCContext and replaced it with the database-first context named BPathEntities:
Repeat the process for any additional controllers and you are done. Hope this helps.