Sei sulla pagina 1di 34

UsingtheEntityFrameworkin

.NETFramework4.0and
VisualStudio2010

HandsonLab
Manual

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 2 of 34
Informationinthisdocument,includingURLandotherInternetWebsitereferences,issubjecttochangewithoutnotice.
Unlessotherwisenoted,theexamplecompanies,organizations,products,domainnames,emailaddresses,logos,
people,places,andeventsdepictedhereinarefictitious,andnoassociationwithanyrealcompany,organization,product,
domainname,emailaddress,logo,person,place,oreventisintendedorshouldbeinferred.Complyingwithall
applicablecopyrightlawsistheresponsibilityoftheuser.Withoutlimitingtherightsundercopyright,nopartofthis
documentmaybereproduced,storedinorintroducedintoaretrievalsystem,ortransmittedinanyformorbyanymeans
(electronic,mechanical,photocopying,recording,orotherwise),orforanypurpose,withouttheexpresswrittenpermission
ofMicrosoftCorporation.
Thenamesofmanufacturers,products,orURLsareprovidedforinformationalpurposesonlyandMicrosoftmakesno
representationsandwarranties,eitherexpressed,implied,orstatutory,regardingthesemanufacturersortheuseofthe
productswithanyMicrosofttechnologies.Theinclusionofamanufacturerorproductdoesnotimplyendorsementof
Microsoftofthemanufacturerorproduct.Linksareprovidedtothirdpartysites.Suchsitesarenotunderthecontrolof
MicrosoftandMicrosoftisnotresponsibleforthecontentsofanylinkedsiteoranylinkcontainedinalinkedsite,orany
changesorupdatestosuchsites.Microsoftisnotresponsibleforwebcastingoranyotherformoftransmissionreceived
fromanylinkedsite.Microsoftisprovidingtheselinkstoyouonlyasaconvenience,andtheinclusionofanylinkdoesnot
implyendorsementofMicrosoftofthesiteortheproductscontainedtherein.
Microsoftmayhavepatents,patentapplications,trademarks,copyrights,orotherintellectualpropertyrightscovering
subjectmatterinthisdocument.ExceptasexpresslyprovidedinanywrittenlicenseagreementfromMicrosoft,the
furnishingofthisdocumentdoesnotgiveyouanylicensetothesepatents,trademarks,copyrights,orotherintellectual
property.
Copyright2007MicrosoftCorporation.Allrightsreserved.
MicrosoftareeitherregisteredtrademarksortrademarksofMicrosoftCorporationintheUnitedStatesand/orother
countries.
Thenamesofactualcompaniesandproductsmentionedhereinmaybethetrademarksoftheirrespectiveowners.

Version1.2

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 3 of 34

TableofContents
LabIntroduction

Objectives
Prerequisites
LabScenarios
VirtualPCConfigurationandSetup
Copy/PasteofCodeRequired
Exercise 1: Model-First Development
Exercise 2: Using Persistence Ignorant Classes
Exercise 3: Building Multi-tier Services with Entities

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 4 of 34

LabIntroduction
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
Thegoalofthesehandsonlab
materialsistogetanoverviewof
someofthenewEntityFramework
featuresin.NETFramework4.0
andVisualStudio2010.

Aftercompletingtheseselfpacedlabs,youwillbeableto:

Begindevelopmentbyfirstcreatingamodelandthen
generatingadatabasefromthatmodel.

UsepersistenceignorantclasseswiththeEntityFramework

Writemultitierservicesusingentities

Prerequisites

LabScenarios

ExperiencewithVisualStudio

ExperiencewithwritingLINQqueries

GeneralexperiencewithbuildingWCFservicesishelpfulbut
notrequired

GeneralexperiencewiththeEntityFrameworkishelpfulbut
notrequired

Thisseriesofexercisesismeanttoshowyouhowtogetstarted
usingthenewEntityFrameworkfeaturesin.NETFramework4.0
andVisualStudio2010.Theseexercisesdemonstratenewpatterns
thatapplicationdeveloperscantakeadvantageofinavarietyof
scenarios.Exercisescanbecompletedasasequenceorcanbe
completedindependently.
SuggestedTimeforCompletion:
60minutes

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 5 of 34

VirtualPCConfigurationandSetup
The Virtual PC machine name is
DataDevLab10DataDevLab10
.
The accounts and passwords used in the following exercises are shown in the following table:
AccountName

AccountPassword

AccountUsage

DataDevLab10

passw0rdpassw0rd

Loginaccountfor
DataDevLab10
Computer

Copy/PasteofCodeRequired
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\
.

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 6 of 34

Exercise 1: ModelFirst 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
applicatio
n.

1. Start
Visual Studio
.
From the Windows task bar, select
Start | All
P
rograms | 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\Entit
y Framework\Exercise1\

Solution Name

Blog

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 7 of 34

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

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 8 of 34

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

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 9 of 34

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 Blogs name
so name the property
Name.
16. Next you need to set the propertys 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

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 10 of 34

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.

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 11 of 34

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:

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 12 of 34

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:

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 13 of 34

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.

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 14 of 34

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.

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 15 of 34

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
BlogClien
t sample.

34. Before you can continue too much farther you need to add some sample Data to our
database. To do so, youre 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.

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 16 of 34

42. Press
F5
to run the Blog Application

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 17 of 34

Exercise 2: Using Persistence Ignorant Classes


Inthisexercise,youwillcreatepersistenceignorantclassesandusenewEntityFrameworkfeaturessuchaslazy
loadingtoenablemanycommondevelopmentpatternswhenusingclassesthatarenottightlycoupledwitha
persistenceframework(EntityFramework).
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.
1. Start
Visual Studio
.
From the Windows task bar, select
Start | All
P
rograms | Microsoft Visual Studio 2010
| Microsoft Visual Studio 2010
menu item.
2. Open the project.
From the File menu, select
File | Open | Project/Solution
menu item.
3. From the Open Project dialog, open the solution file at C:\HOLs\Entity
Framework\
Exercise2\Blog\Blog.sln
If you are not continuing from Exercise 1, you will need to setup the EFBlog database for
this exercise.
4. Open the SQL Script.
Right click on the
Blog Solution
in
Solution Explorer
, click
Add | Existing Item
5. From the
Add Existing Item
dialog, open the file:
C:\HOLs\Entity Framework\

Exercise2\BlogAll.sql
You may need to select to show
All Files (*.*)
6. Click
Add.
7. Open
BlogAll.sql
, right click on the editor and select
Execute SQL

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 18 of 34

8. Click
Connect
Add
persistence
ignorant
classes

9. Turn off Code Generation


Double click BlogModel.edmx in the BlogModel project to open the Entity Designer.
Right click on the design surface to see the properties window. Set the Code
Generation Strategy property to None.

10. Add a code file for Blog.cs file to the BlogModel project.
From the
Solution Explorer
, right click on the
BlogModel
project and from the context
menu select
Add | New Item | Class
.
11. Now we will create our POCO objects. Type the name
Blog.cs
for the class name and
click
Add
to add the class to your project.

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 19 of 34

12. When the file opens, type in or copy and paste the following code into the file to add
an implementation for a Blog. This class implementation includes the serialization
attributes for DataContract serialization which will be used in Exercise 3.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
namespace BlogModel
{
[DataContract(IsReference = true)]
public class Blog
{
[DataMember]
public int BlogID
{
get;
set;
}
[DataMember]
public string Name
{
get;
set;
}
[DataMember]
public string Owner
{
get;
set;
}
[DataMember]
public List<Post> Posts
{
get { return _posts; }
set { _posts = value; }
}
List<Post> _posts = new List<Post>();
}
}

13. Repeat steps 13 15 to add code files for the Tag class and Post class
Tag.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
namespace BlogModel

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 20 of 34
{
[DataContract(IsReference = true)]
public class Tag
{
[DataMember]
public int TagID
{
get;
set;
}
[DataMember]
public string Name
{
get;
set;
}
[DataMember]
public List<Post> Posts
{
get { return _posts; }
set { _posts = value; }
}
List<Post> _posts = new List<Post>();
}
}

Post.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
namespace BlogModel
{
[DataContract(IsReference = true)]
public class Post
{
[DataMember]
public int PostID
{
get;
set;
}
[DataMember]
public DateTime CreatedDate
{
get;
set;
}
[DataMember]

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 21 of 34
public DateTime ModifiedDate
{
get;
set;
}
[DataMember]
public string Title
{
get;
set;
}
[DataMember]
public string PostContent
{
get;
set;
}
[DataMember]
public Blog Blog
{
get;
set;
}
[DataMember]
public int BlogBlogID
{
get;
set;
}
[DataMember]
public List<Tag> Tags
{
get { return _tags; }
set { _tags = value; }
}
private List<Tag> _tags = new List<Tag>();
}
}

Add a
context class

With code generation turned off we no longer have a BlogContext ObjectContext


implementation. In this next step, you will create your own BlogContext.
14. Add a code file for BlogContext to the BlogModel project.
From the
Solution Explorer
, right-click on the
BlogModel
project, and from the context
menu select
Add | New Item | Class
.
15. Type the name
BlogContext.cs
for the class name and click
Add
to add the class to your
project.

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 22 of 34

16. When the file opens, type in or copy and paste the following code into the file to define
the BlogContext class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
namespace BlogModel
{
public class BlogContext : ObjectContext
{
public BlogContext()
: base("name=BlogContext", "BlogContext")
{
}
public ObjectSet<Blog> Blogs
{
get
{
if (_Blogs == null)
{
_Blogs = base.CreateObjectSet<Blog>("Blogs");
}
return _Blogs;
}
}
private ObjectSet<Blog> _Blogs;
public ObjectSet<Post> Posts
{
get
{
if (_Posts == null)
{
_Posts = base.CreateObjectSet<Post>("Posts");
}
return _Posts;
}
}
private ObjectSet<Post> _Posts;
public ObjectSet<Tag> Tags
{
get
{
if (_Tags == null)
{
_Tags = base.CreateObjectSet<Tag>("Tags");
}
return _Tags;
}
}

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 23 of 34

private ObjectSet<Tag> _Tags;


}
}

17. Run the application by pressing


F5
or selecting the menu item
Debug | Start
Debugging
. You will see the BlogClient run and you can browse the blogs and posts as
before, but this time you are using persistence ignorant classes.

Update the
classes to
use lazy
loading with
POCO
classes

The current POCO implementation uses explicit loading. When performing explicit
loads is not a concern, it is possible to use lazy loading (also known as deferred loading)
to load associated entities whenever a property is accessed for the first time. This is
done by making relationship navigation properties (such as Blog.Posts or Post.Tags)
virtual. The Entity Framework will create a proxy type at runtime that knows how to
perform a load so that no additional code changes are necessary. In the next series of
steps you will enable the use of lazy loading.
18. From the
Solution Explorer
, double-click on the
Blog.cs
file in the
BlogModel
project.
19. Change the Posts property definition to be virtual:
public virtual List<Post> Posts

20. Enable lazy loading


From the
Solution Explorer
, double-click on the
MainWindow.xaml.cs
file in the
BlogClient
project. If this file is not visible, click on the + sign next to
MainWindow.xaml.
21. Locate the MainWindow constructor and change the code to turn on deferred loading:
public MainWindow()
{
InitializeComponent();
_context = new BlogContext();
_context.ContextOptions.LazyLoadingEnabled = true;
this.MainGrid.DataContext = _context.Blogs;

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 24 of 34

22. You can now remove contents of the event handler method
BlogList_SelectionChanged
. Locate this method, select the method and delete it the
contents.
23. Run the application by pressing
F5
or selecting the menu item
Debug | Start
Debugging
. You will see the BlogClient run and you can browse the blogs and posts as
before, but this time you are using persistence ignorant classes that use lazy loading.

24. You are now ready to move to the next exercise.

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 25 of 34

Exercise 3: Building Multitier Services with Entities


In this exercise, you will setup a WCF service that exposes functionality from a BlogRepository, and a
client that consumes it. This exercise demonstrates one way to create an N-Tier application using WCF
to expose a select set of methods to the client. In many cases when you want to expose CRUD
functionality to the client you will want to use ADO.NET Data Services. For more information on using
ADO.NET Data Services with the Entity Framework check out the ADO.NET Data Services Hands On
Lab. (Note: It is important to move to a multi-tier architecture only when there is a real need to do so.
There are several articles online that describe when it is appropriate to implement a multi-tier
solution.)
Tasks

Detailed Steps

Open the
project file
and setup
the
database

If you are continuing from Exercise 2, 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.
1. Start
Visual Studio
.
From the Windows task bar, select
Start | All
P
rograms | Microsoft Visual Studio
2010 | Microsoft Visual Studio 2010
menu item.
2. Open the project.
From the File menu, select
File | Open | Project/Solution
menu item.
3. From the Open Project dialog, open the solution file at C:\HOLs\Entity
Framework\
Exercise3\Blog\Blog.sln
If you are not continuing from Exercise 2, you will need to setup the EFBlog database
for this exercise.
4. Open the SQL Script.
Right click on the
Blog Solution
in
Solution Explorer
, click
Add | Existing Item
5. From the
Add Existing Item
dialog, open the file:
C:\HOLs\Entity Framework\
Exercise3\BlogAll.sql
You may need to select to show
All Files (*.*)
6. Click
Add.
7. Open
BlogAll.sql
, right click on the editor and select
Execute SQL

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 26 of 34

8.

Add
Repository

Click
Connect
It is a common design pattern to implement a repository where domain specific
methods are implemented. In this next series of steps, you will implement a
repository class for Blogs that takes advantage of the interface implementation you
added.

9. From the Solution Explorer, add a new class to the BlogModel project.
Right-click on the
BlogModel
project and from the context menu select
Add | New
Item | Class
10. From the
Add New Item
dialog, enter a name for the code file:
BlogRepository.cs
Click
Add
to add the new class to your project.
11. When the file opens, type in or copy and paste the following code into the file to
add the basic repository:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BlogModel
{
public class BlogRepository
{
BlogContext _context;
public BlogRepository(BlogContext context)
{
_context = context;
}
}

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 27 of 34
}

12.
Add a business logic method to return all blogs

public IEnumerable<Blog> Blogs


{
get
{
return _context.Blogs;
}
}

13. Next add a business logic method to return posts from a Blog. This repository
method uses the LoadProperty method on the ObjectContext, which is an explicit
call to request the related entities from the database.

public IEnumerable<Post> GetPosts(Blog blog)


{
_context.Blogs.Attach(blog);
_context.LoadProperty(blog, b => b.Posts);
return blog.Posts;
}

14. Add a business logic method to update a post. For now, this implementation will
just call the Validate method.

public string UpdatePost(Post post)


{
string result = "Updated!";
try
{
post.Validate();
}
catch(Exception e)
{
result = e.Message;
}
return result;
}

Update
Post to
include
Validate
method

Update
the Blog
Client to
use your
repository

15. Double click on Post.cs to open.


16. Add Validate() method to the Post class.
public void Validate()
{
if (CreatedDate > DateTime.Now)
{
throw new Exception("Post from the future!");
}
}

In this next series of steps, you will update your Blog client to use the
BlogRepository.
17. From the
Solution Explorer
double-click on the
MainWindow.xaml.cs
file that
contains the presentation logic to display blogs.

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 28 of 34

18. At the top of the MainWindow class where the BlogContext is declared. Change the
type from BlogContext to BlogRepository.

BlogRepository _repository;

19. In the MainWindow constructor where _context is assigned and used. Change this
method to create a new BlogRepository and to use the Blogs property by replacing
the code in the constructor with the code below:

public MainWindow()
{
InitializeComponent();

_repository = new BlogRepository(new BlogContext());


this.MainGrid.DataContext = _repository.Blogs;

20. Change the UpdateButton_Click method to call the UpdatePost method on the
repository by replacing the code in the method with the code below:

private void UpdateButton_Click(object sender, RoutedEventArgs e)


{
Post post = PostList.SelectedItem as Post;
if (post != null)
{
MessageBox.Show(_repository.UpdatePost(post));
}
}

21. Change the BlogList_SelectionChanged method to call the GetPosts method on the
repository by replacing the code in the method with the code below:
private void BlogList_SelectionChanged(object sender,
SelectionChangedEventArgs e)
{
Blog blog = BlogList.SelectedItem as Blog;
_repository.GetPosts(blog);
}

22. Run the solution


From the
Debug
menu select
Debug | Start Debugging

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 29 of 34

Create a
WCF
service
library

23. Add a WCF Service project


From the menu bar, select
File | Add | New Project

24. From the Add New Project dialog select


Visual C# | WCF | WCF Service Library
Fill in the names and location for the project:
Name

BlogService

Location

C:\HOLs\Entity Framework\Exercise1\Blog

Note
: Set the Location to C:\HOLs\Entity Framework\Exercise3\Blog if you are not
continuing from a previous model.
Click
OK
to add the project to your solution.
25. Add a project reference to System.Data.Entity.
From the
Solution Explorer
, locate the new BlogService project, right click on the
BlogService
project name, and from the context menu select
Add Reference

26. From the


Add Reference
dialog, click on the
.NET
tab and select
System.Data.Entity.
Click
OK
to add the project reference.
27. Add a project reference to BlogModel.

From the
Solution Explorer
, locate the new BlogService project, right click on the
BlogService
project name, and from the context menu select
Add Reference

28. From the


Add Reference
dialog, click on the
Projects
tab and select
BlogModel.
Click
OK
to add the project reference.

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 30 of 34

29. The service will be making a connection to the database so you will need to add the
connection string to the app.config file in the BlogService project. In the
Solution
Explorer
, under the
BlogService
project, double click on the
app.config
file to open
it.
30. Paste in the connection string tag underneath the configuration tag.
<connectionStrings>
<add name="BlogContext"
connectionString="metadata=res://*/BlogModel.csdl|res://*/BlogModel.ssdl|res:
//*/BlogModel.msl;provider=System.Data.SqlClient;provider connection
string=&quot;Data Source=.\SQLEXPRESS;Initial Catalog=EFBlogs;Integrated
Security=True;Pooling=False;MultipleActiveResultSets=True&quot;"
providerName="System.Data.EntityClient" />
</connectionStrings>

In this exercise you will not be using lazy loading so it is important to remove the
virtual Posts property on the Blog class.
31. From the
Solution Explorer
, double-click on the file
Blog.cs
in the
BlogModel
project.
32. Change the Posts property definition to not be virtual:
public List<Post> Posts

Add
service
methods
for your
repository

33. Open the IService1.cs file


From the
Solution Explorer
, locate the new
BlogService
project and double-click on
the
IService1.cs
file.
34. Near the top of the file, add a new using statement for
BlogModel
.
using BlogModel;

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 31 of 34

35. Remove the contents of the IService1 ServiceContract that are pre-filled with
sample operation methods and replace them with the code below. This will define
the set of operations we will use with the repository and context.
[ServiceContract]
public interface IService1
{
[OperationContract]
IEnumerable<Blog> GetBlogs();
[OperationContract]
IEnumerable<Post> GetPosts(Blog blog);
[OperationContract]
string UpdatePost(Post post);
}

36. Open the Service1.cs file


From the
Solution Explorer
, locate the
BlogService
project and double-click on the
Service1.cs
file
.
37. Near the top of the file, add a new using statement for
BlogModel
.
using BlogModel;

38. Remove the contents of Service1.cs that are pre-filled with sample operation
methods.
39. Implement GetBlogs
Type in or copy and paste the code below to implement the GetBlogs service
method on Service1. This method creates a new BlogContext and BlogRepository
and returns all of the Blogs.
public IEnumerable<Blog> GetBlogs()
{
using (BlogContext context = new BlogContext())
{
BlogRepository repository = new BlogRepository(context);
return repository.Blogs.ToArray();
}
}

40. Implement GetPosts


Type in or copy and paste the code below to implement the GetPosts service
method on Service1. This method creates a new BlogContext and BlogRepository
and calls GetPosts.
public IEnumerable<Post> GetPosts(Blog blog)
{
using (BlogContext context = new BlogContext())
{
BlogRepository repository = new BlogRepository(context);
return repository.GetPosts(blog).ToArray();
}
}

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 32 of 34

41. Implement UpdatePost


Type in or copy and paste the code below to implement the UpdatePost service
method on Service1. This method creates a new BlogContext and BlogRepository
and calls UpdatePost.
public string UpdatePost(Post post)
{
using (BlogContext context = new BlogContext())
{
BlogRepository repository = new BlogRepository(context);
return repository.UpdatePost(post);
}
}

Update
the
BlogApplic
ation to
use the
BlogServic
e

42. Build your solution by selecting from the menu


Build | Build Solution
.
43. Add a service reference to BlogClient
From the
Solution Explorer
, locate the
BlogClient
project. Right-click on the
BlogClient
project name, and from the context menu select
Add Service Reference
44. From the
Add Service Reference
dialog click on the
Discover
button.
45. Select the service that is found and click
OK
to add the service reference.

46. From the


Solution Explorer
, double-click on the
MainWindow.xaml.cs
file to open
it.
47. Near the top of the file, add this using statement to use the service reference.

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 33 of 34
usingBlogClient.ServiceReference1

48. MainWindow currently uses the BlogRepository directly. In this step you will
replace that with the service you implemented. Replace the BlogRepository
declaration at the beginning of MainWindow class with a Service1Client
declaration.
Service1Client _client;

49. Next replace the constructor for MainWindow with an implementation that
instantiates a new Service1Client and calls the GetBlogs method.
public MainWindow()
{
InitializeComponent();
_client = new Service1Client();
this.MainGrid.DataContext = _client.GetBlogs();
}

50. Next replace the UpdateButton_Click method for MainWindow with an


implementation that uses the service client.
private void UpdateButton_Click(object sender, RoutedEventArgs e)
{
Post post = PostList.SelectedItem as Post;
if (post != null)
{
post.CreatedDate = post.CreatedDate.AddDays(2);
MessageBox.Show(_client.UpdatePost(post));
this.MainGrid.DataContext = _client.GetBlogs();
}
}

51. Finally replace the BlogList_SelectionChanged method for MainWindow with an


implementation that uses the service client. When performing service operations, it
is important to remember that the entities that are returned are new instances so
the returned posts must be copied to the blog collection.
private void BlogList_SelectionChanged(object sender,
SelectionChangedEventArgs e)
{
Blog blog = BlogList.SelectedItem as Blog;
if (blog.Posts.Count == 0)
{
foreach (Post post in _client.GetPosts(blog))
{
blog.Posts.Add(post);
}
}
}

52. Press
F5
to run the BlogClient

Using the Entity Framework in .NET 4.0 and Visual Studio 2010
Microsoft Hands-on Labs
Page 34 of 34

Update
the
repository
to perform
a save

In this set of steps you will modify the UpdatePosts method on the BlogRepository to
save the updated post.
53. From the
Solution Explorer
, double-click on the
BlogRepository.cs
file from the
BlogModel
project to open it.
54. Locate the UpdatePost method on line 30 and replace the method contents with
the code below that uses a new Entity Framework method,
ChangeObjectState
to
mark the entity as modified.
public string UpdatePost(Post post)
{
string result = "Updated!";
try
{
post.Validate();
_context.Posts.Attach(post);
_context.ObjectStateManager.ChangeObjectState(post,
System.Data.EntityState.Modified);
_context.SaveChanges();
}
catch(Exception e)
{
result = e.Message;
}
return result;
}

55. Press
F5
to run the BlogClient. Click the
Update
button to see the update take
place.

Additional Resources

MSDN Data Platform Developer Center

EF Design Blog

ADO.NET Entity Framework


MSDN Documentation

The ADO.NET Entity Framework Overview


MSDN Technical Article

ADO.NET Entity Framework and LINQ to Entities


MSDN Forum

Entity Framework FAQ

Potrebbero piacerti anche