Getting Started with Entity Framework 4 – Simple Model First Example

This is the first in a series of posts on getting started with the new features in Entity Framework 4 based on the demos I did in my session at TechEd Europe in Berlin last week (Nov 2009).

When adding an Entity Data Model to a project you are given the option to:

  • Generate the Model from an existing database (SQL Server, Oracle etc) or
  • Start with an Empty Model and create your conceptual model (sometimes referred to as Application Model or Domain Model) first – adding new Entities and Associations between Entities.

Unfortunately in version one of the Entity Framework the button “Empty model” was one of those “buttons that should never be pressed” (Reference the Xmas episode of Dr Who). Put simply – it took you down a path to many, many issues which were best avoided and the recommendation in the v1 days was to never use it.

Fortunately in the betas of Entity Framework 4 things have got a lot better. You can now safely click on “Empty Model” and continue to sensibly create a working solution.

Hence, lets start with anEmpty model.

image

Once you have your empty model you can add Entities and Associations by right clicking on the design surface:

image

Lets add two Entities – Category and Product, which you will likely be used to from the sample database Northwind. Once these are added we can then add a single association between Category and Product which is visualised in the design surface as the Navigation Properties on each Entity and the 1:Many association:

image 

We now have a “finished” conceptual model but with no mapping to database tables. Interestingly there is no way to start to map Entities to tables until you do at least one “Generate Database from Model”:

image

Which gives you the Generate Database Script Wizard:

image

When you click Finish two things will happen.

  • A DDL script will be written to the file system and will be included into the project. In this case ModelFirstModel.edmx.sql
  • The Entity Data Model will be updated – a new mapping file and store schema file will be generated. Remember that the Entity Data Model (EDM) is made up of three schemas – Conceptual, Mapping and Store

You get the option to update the Entity Data Model or not – but TBH the only option is to go with Yes. The update of the EDM is 100% destructive:

image

Note the DDL script is not automatically run against your database. Which is a good thing as it is also 100% destructive:

image

Hence all that is then left to do is to actually execute the DDL script to create the database, which for me I tend to do inside SQL Server Management Studio. You will then see that the Entities and Associations are now mapped and you can begin to customise those mappings.

That has covered the simple stuff with Model First but I plan to revisit this topic in the near future and look at why and how you might use it in a real solution.