Using the Entity Framework in
.NET Framework 4.0 and
Visual Studio 2010
Hands-on Lab
Manual
Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 3 of 33
Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
The names of manufacturers, products, or URLs are provided for informational purposes only and Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links are provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission received from any linked site. Microsoft is providing these links to you only as a convenience, and the inclusion of any link does not imply endorsement of Microsoft of the site or the products contained therein.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.
Copyright © 2007 Microsoft Corporation. All rights reserved.
Microsoft are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.
The names of actual companies and products mentioned herein may be the trademarks of their respective owners.
Version 1.2
Table of Contents
Lab Introduction 4
Objectives 4
Prerequisites 4
Lab Scenarios 4
Virtual PC Configuration and Setup 5
Copy/Paste of Code Required 5
Exercise 1: Model-First Development 6
Exercise 2: Using Persistence Ignorant Classes 16
Exercise 3: Building Multi-tier Services with Entities 24
Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 3 of 33
Lab Introduction
Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 3 of 33
Each Exercise in this lab is designed to be completed independently if you do not have time to complete all Exercises in one sitting.
Objectives
The goal of these hands-on lab materials is to get an overview of some of the new Entity Framework features in .NET Framework 4.0 and Visual Studio 2010. / After completing these self-paced labs, you will be able to:§ Begin development by first creating a model and then generating a database from that model.
§ Use persistence ignorant classes with the Entity Framework
§ Write multi-tier services using entities
Prerequisites
/ § Experience with Visual Studio§ Experience with writing LINQ queries
§ General experience with building WCF services is helpful but not required
§ General experience with the Entity Framework is helpful but not required
Lab Scenarios
/ This series of exercises is meant to show you how to get started using the new Entity Framework features in .NET Framework 4.0 and Visual Studio 2010. These exercises demonstrate new patterns that application developers can take advantage of in a variety of scenarios. Exercises can be completed as a sequence or can be completed independently.Suggested Time for Completion: 60 minutes
Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 33 of 33
Virtual PC Configuration and Setup
The Virtual PC machine name is DataDevLab10DataDevLab10.
The accounts and passwords used in the following exercises are shown in the following table:
Account Name / Account Password / Account UsageDataDevLab10 / passw0rdpassw0rd / Login account for DataDevLab10 Computer
Copy/Paste of Code Required
You will be asked to copy/paste code snippets to complete this lab. In order to do this, you need to open a copy of this lab manual inside the Virtual Machine. This specific lab can be found here: C:\HOLs\Entity Framework\.
Exercise 1: Model-First Development
In this exercise, you will design a model for a blogging application that contains three entities: Blogs, Posts, and Tags. You will then use that model to generate a database schema.
Tasks / Detailed Steps /Create a model for the Blog application. / 1. Start Visual Studio.
From the Windows task bar, select Start | All Programs | Microsoft Visual Studio 2010 | Microsoft Visual Studio 2010 menu item.
2. When Microsoft Visual Studio 2010 opens, create a new Class Library Project.
From the File menu, select New | Project…
3. In the New Project dialog, select Visual C# | Windows | Class Library
Fill in the names and location for the project:
Name / BlogModel
Location / C:\HOLs\Entity Framework\C:\HOLs\Entity Framework\Exercise1\
Solution Name / Blog
4. Click OK to create the project.
5. From the Solution Explorer, right-click on the project name BlogModel and select Add | New Item …
This opens the Add New Item dialog.
6. In the Add New Item dialog, select Data under Visual C# Items, and ADO.NET Entity Data Model.
Give the item the name “BlogModel.edmx”.
Click Add to bring up the Entity Data Model Wizard.
7. Click Add.
8. From the Entity Data Model Wizard, select Empty Model and click Finish. This will add several references to your project as well as the empty BlogModel.edmx file. You are now ready to begin adding entities to your model.
9. From the Solution Explorer, double-click on the BlogModel.edmx file to open the Entity Data Model Designer.
10. Rename your context
Right-click on the designer surface and from the context menu select Properties. From the property list, set the Entity Container Name to BlogContext
11. You will need to display the Toolbox window to add new entities to the model. Click on the Toolbox link on the designer surface to display the Toolbox window.
12. From the Toolbox window, drag an Entity item to the model designer surface. This will add an entity named Entity1 to your model. Right click the Entity1 shape and select Properties to open the Properties window.
13. From the Properties window, set the following properties:
Name / Blog
Entity Set Name / Blogs
14. From the Entity Data Model Designer, select the Blog entity. Next right click on the Id property and select Properties. From the Properties window rename the Id member to BlogID. Also change the Type property to Int32. BlogID is the key for this entity, so set the Entity Key property to True.
Name / Type / EntityKey
BlogID / Int32 / True
15. Next you will add additional properties to the Blog entity. From the Entity Data Model Designer, select the Blog entity. Next right click in the top portion of the entity and select Add | Scalar Property. This will add a new property. This property will be the Blog’s name so name the property Name.
16. Next you need to set the property’s type. Right click on the Name property and select Properties. From the Properties window, set the Type to String.
Name / Name
Type / String
17. Repeat steps 15 and 16 to add another string property named Owner.
Name / Owner
Type / String
18. You have now added an entity to your model. There are two other entities that need to be added to the model, one for a Post and one for a Tag. Repeat steps 12 – 16 to add two additional entities and their properties:
Post Entity
Name / Post
Entity Set Name / Posts
Properties:
Name / Type / EntityKey
PostID / Int32 / True
CreatedDate / DateTime / False
ModifiedDate / DateTime / False
PostContent / String / False
Title / String / False
Tag Entity
Name / Tag
Entity Set Name / Tags
Properties:
Name / Type / EntityKey
TagID / Int32 / True
Name / String / False
19. Now that you have added the entities to the model you can add relationships between these entities. The first relationship that you will add is between a Blog and a Post. Right click on the Blog entity and select Add | Association… This will open the Add Association dialog.
20. From the Add Association dialog, fill in the association details of the Blog to Post relationship using the information below.
Notice the new checkbox titled “Add foreign key properties to the ‘Post’ Entity”. This will add the necessary foreign key properties to the model and set up the needed referential constraint. Click OK to add the association.
To see the referential constraint that was setup, double-click the association:
Click OK.
21. Next you will add the relationship between a Post and a Tag. A Post can have many Tags and a Tag can be associated with many Posts so this is a Many to Many relationship. Right click on the Post entity and select Add | Association… This will again open the Add Association dialog.
22. From the Add Association dialog, fill in the association details of the Post to Tag relationship using the information below:
Click OK to add the association. Your model will know look like this:
23. The model is now complete and you should save the BlogModel.edmx file by selecting the menu File | Save BlogModel.edmx.
24. You are now ready to create the database from this model.
Generate a database schema from the model / 25. To generate a database schema from the model, you will first need to create an empty database to store the schema. For this example you will be using a local SqlExpress database. From the menu bar, select View | Server Explorer to open the Server Explorer window.
26. From the Server Explorer window, right click on the Data Connections node and select Create New SQL Server Database… to open the Create New SQL Server Database dialog.
27. In the Create New SQL Server Database dialog, fill in the dialog box to create a local database EFBlogs with the information below:
Click OK to create the database.
28. You can now create the database schema for the Blogs database. From BlogModel.edmx right-click on the designer surface and choose Generate Database from Model… This will open the Generate Database Wizard.
29. From the Generate Database Wizard, select the connection to the EFBlogs database and select the “No, exclude sensitive information from the connection string” option. Click Next to continue to the summary page.
30. From the Summary page you can look over the DDL statements for the database schema. Notice that foreign keys have been added to the Post and Tags tables and that a PostTags table has been included as a link table to support the many-to-many relationship between Posts and Tags. Click Finish to save the .sql file to your project.
31. You will be prompted that this operation will overwrite the msl and ssdl information in your edmx file. Click Yes to continue.
32. With the BlogModel.edmx.sql file open (the DDL script that was just created), right click on the editor and select Execute SQL to run the script and create your database. You will be presented with the Connect to Database Engine dialog.
33. Select the database connection that we just created using Server Explorer, and click OK. You should see a message “The command(s) completed successfully” when your script has finished creating your new database.
Run the BlogClient sample. / 34. Before you can continue too much farther you need to add some sample Data to our database. To do so, you’re going to run a pre-written SQL script that will add this sample data.
35. Open the SQL Script to populate the Blog database with data.
Right click on the BlogModel project in Solution Explorer, click Add | Existing Item…
36. From the Add Existing Item dialog, open the file:
C:\HOLs\Entity Framework\Exercise1\BlogData.sql
You may need to select to show All Files (*.*)
37. Click Add.
38. Open BlogData.sql, right click on the editor and select Execute SQL
39. Add the BlogClient project to your Blog solution
From the Solution Explorer, right-click on the solution Solution (‘Blog’) and form the context menu select Add | Existing Project …
40. From the Add Existing Project dialog, select the project file at:
C:\HOLs\Entity Framework\Exercise1\BlogClient\BlogClient.csproj
41. Set the BlogClient sample as the startup project.
42. Press F5 to run the Blog Application
Exercise 2: Using Persistence Ignorant Classes
In this exercise, you will create persistence ignorant classes and use new Entity Framework features such as lazy loading to enable many common development patterns when using classes that are not tightly coupled with a persistence framework (Entity Framework).
Tasks / Detailed Steps /Open the project file and setup the database / If you are continuing from Exercise 1, you can skip to step 9. Otherwise follow the steps below to open the Visual Studio solution containing the Blog EDM, entity classes, and WPF client application.