Sunday, February 26, 2012

Building an EF 4 Model Assembly for Pubs DB

For this EF building block, I am going to build a Model Assembly. This assembly will contain the Model for the famous Pubs database. You can download Pubs along with Northwind from Microsoft.

I like the idea of separating my model for the rest of my app. I will use this model to LINQPad (and perhaps WinForms, WPF, etc.). I can link it directly to my UI or through a labyrinth of assemblies that I put between my UI (if I even have one).

Since you don’t have to write any actual code, the steps below should work for both C# and VB. They were tested on both Express Editions.

So here we go:

  1. Create a new Project, call it PubsModel
    I like to use the pattern [SomeName]Model, where SomeName may be the name of the application or database.
  2. Delete Class1.cs or Class1.vb
    Microsoft want to be helpful, I’ve probably destroyed a thousand Class1s
  3. Project => Add New Item. (Alt+Shift+A)
  4. Select ADO.NET Entity Data Model
  5. Name it PubsModel.edmx
  6. In the Entity Data Model Wizard, select Generate from database
  7. In the next window, select pubs.mdf. If pubs.mdf is not on the list, you will need to click New Connection to add it to the list.
    Since this is Visual Studio Express, I am only allowed to make a Microsoft SQL Server Database File connection.
  8. Set the value for Save entity connection settings in App.Config as: to pubsEntities.
  9. Visual Studio asks you if you want to make a local copy of the database file.
    I usually answer “No” so I can play with the data with Microsoft SQL Server Management Studio. Of course any change I make to the data will affect the “Master” database.
  10. Select Tables, Views and Stored Procedures.
  11. Keep the defaults for Plurlaize or singularize generated object names and Include foreign key columns in the model.
  12. Set Model Namespace to pubsModel
  13. Click Finish.

After some churning and reformatting, you will get a model that looks like this

.pubs_model

No comments: