.Net Development & General Tech Related News

TUTORIAL: Entity Framework v2.0 – Model First using Visual Studio 2010 and .Net 4.0

May 20th, 2009 Posted in .Net, ASP.Net, C#, Entity Framework, Tutorials, ado.net, visual studio

Following up on my recent post about the improvements to the Entity Framework in .Net 4.0 this is the first in a series of posts examining some of the new features and showing you how to put some of them into practice.

In this post I am going to look at one of the most anticipated features, Model First.  In the first version of the Entity Framework, you took a pre-existing database and the tools would generate your entity model for you.  In v2.0, you now have the option of creating your entity model first and then generating your database DDL from your finished model.

To follow this tutorial you will need Visual Studio 2010 Beta 1, .Net Framework 4.0 Beta 1 installed, SQL 2005 or 2008 / SQL Express.

Please bear with me and let me know if there are any parts of this tutorial that are not completely clear.  I am new to writing these! So any comments welcome….

Creating your project and adding your blank entity model

Open Visual Studio 2010 and create a new Dynamic Data Entities Web Application project(you could another project type to host your entity model, such as an ASP.Net Web Application).

Once your project has been created add a new ADO.Net Entity Data Model to the project. 

add_model_object

You will then be asked about what the model should contain.  As with version 1 of the Entity Framework, you have two options, Generate from Database and Empty Model.  To a large extent, the latter was redundant in the first version of the framework, but with version 2 it becomes very useful.  Select Empty Model and click Finish.

choose_empty_model


Adding an entity and scalar properties to your model

You will now be presented with your empty model designer ready for you to add your entities.  Right click on the designer and select Add –> Entity…  For this example we will name our entity “Customer” and the entity set “Customers”.  This will create your Customer entity in the designer.

You will now need to add some properties to the entity.  You can do this by right clicking the entity and Add –> Scalar Property and then selecting the data type of the property. Do this and create two string scalar properties for Name and Email.


Adding complex types

You should now have a Customer entity with properties for the customer’s name and email address. A complex type is essentially a property that can contain sub properties.  To display this we are going to create one for the customer’s mailing address.

In your model browser, right click on the “Complex Types” folder and select Create Complex Type.  Rename this created type “Address”.  Now right click on the Address object you have created and select Add –> Scalar Property –> String.  Rename the created property “Line 1”.  Repeat this, adding properties for Line 2, Town, County, Post Code (you could use City, State, Zip if you are in the U.S. for example).

entity_created_add_scalar

Once you have created your complex type, you can add this to your Customer entity by right clicking the entity and selecting Add –> Complex Property. If you name your property Address, then the property type should automatically be set to Address, which is what we have just created.  You can check this and alter the type via the properties of the complex property (that’s a lot of properties :) )

 

Create some additional entities

Once I had created my Customer entity, I then went through the same steps to create two additional entities for Order and Product. If you do this, then you should end up with something like below.

finished_entities


Adding entity associations

Now that we have our entities for Customer, Order and Product, we need to tell the model how the entities are associated.  For example, a customer will have related orders and an order will have related products.

To add our first association, right click the Customer entity and select Add –> Association. You will then be presented with the dialog shown below to actually define the association.  As you can see, the primary entity for this association is Customer which is related to Order with a multiplicity of one-to-many.  Here is where we also set the navigation properties which will allow us to access related entities.  So for example, the Customer entity will have a navigation property of “Orders”.  There is also a plain English description of the association you are about to create to ensure that you are creating it correctly.

create_association  

Once you are happy click ok and the association will be shown on your model connecting the Customer and Order entities.

We now need to also create an association between the Order and Product entities using the same steps as above, but this time the properties of the association are slightly different as the multiplicity is many-to-many as show below.

many-to-many-association


Generating the database

Ok, so we have our model containing our entities.  Our entities have their properties and their associations, but we still do not have a database for our model to map to.  This is the bit I really like.  Right click on the model designer area and click “Generate Database Script From Model…”.

This will then open the standard database connection dialog we are all used to in Visual Studio. Add a connection, select your server and enter a name for your database (use a name that does not already exist, I called mine “ModelFirstTestDb”…..original I know!), then click OK.  You should then be prompted to create the database as seen below, so click Yes to create the database.

confirm_database_create

You should now see your new connection selected and the option to store the credentials in the web.config should be checked. Click next and the database schema scripts (DDL) will be generated for you and you will be presented with the generated script as below.  Take a minute to have a look through the DDL and see how it has created the tables and fields.  In the image below you can see the fields that have been generated to map to the complex type for the Customer address we created earlier.

generated_ddl

Now we just need to click Finish and we will be warned that our existing mappings and store schema will be overwritten, click Yes to continue.

ssdl_warning


Execute your DDL

Now you need to take the generated script and execute it against your database.  The database itself will have been created, but in this beta version you still need to execute the scripts manually.  The ADO.Net team have indicated that this will not be the case in the final version.


Running your Dynamic Data Entities application

If you now open the Global.asax.cs file in your project and add the following line in the RegisterRoutes method, you should be able to run your application and see your new model and database in action;

DefaultModel.RegisterContext(typeof(Model1Container),new ContextConfiguration() { ScaffoldAllTables = true });


Kick It on DotNetKicks.com
Share this Post:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DotNetKicks
  • Reddit
  • StumbleUpon
  • TwitThis
No TweetBacks yet. (Be the first to Tweet this post)

Technorati Tags: , , , ,

Tags: , , , ,

  1. 6 Responses to “TUTORIAL: Entity Framework v2.0 – Model First using Visual Studio 2010 and .Net 4.0”

  2. By Mehdin on Jul 2, 2009

    Wow, looks like Entity Framework 2.0 will be finally useful.
    Will it be possible to create POCO using model designer? POCO will be supported, but will we be able to edit them using the designer.
    What about lazy loading and performance comparing to pure ADO.NET objects?

  3. By Gary Pretty on Jul 2, 2009

    Looks like this will be possible. Just do a Google to find out more as there are plenty of detailed posts on the matter, such as this one discussing POCO in Entity Framework 4.

  4. By Dennis on Jul 21, 2009

    How to execute the generated script/DLL against my database, if I’m using MDF or SDF?

    Haven’t been able to figure it our, despite intensive search.

  5. By Larry Aultman on Jul 26, 2009

    I have done a model first with some complex types. The SQL script implements all these as column in the same db table. I was expecting different tables. What real advantage is this? It certainly doesn’t look like normalized database tables. In my case there are cases where regular old LINQ to SQL works very well (such as transaction processing) while more complex stuff like customer and client management benefit from entity models.
    Where do you draw the lines? The academic views really don’t do well in the real world.
    In our practical world we have business logic out on the edge and at other levels as the data is crunched, filterd, parsed, and spread around.
    Just looking for advice before we start this next round of development/enhancement.

  6. By Gary Pretty on Jul 26, 2009

    Larry, this is a tough one to answer. You are right that the academic views dont do so well in the real world in many areas. Entity Framework has not been used so much yet in commercial environments from what I can see with many people waiting for the features we see in this upcoming version.

    Even then though, I would be deciding on a case by case basis when and how to implement it, rather than adopting a blanket approach.

  7. By kwanchaiw on Apr 13, 2010

    Thank for this tutorial,I ‘ll try n try n try…

Post a Comment