Tải bản đầy đủ (.pdf) (10 trang)

Lập trình .net 4.0 và visual studio 2010 part 26 pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (418.87 KB, 10 trang )

CHAPTER 8

  

175
Entity Framework
Entity Framework (EF) is Microsoft’s Object Relational Mapping (ORM) solution and was first released
with .NET 3.5SP1. Entity Framework received much criticism when it was first released and the team at
Microsoft has been hard at work to address some of these criticisms in the latest version.

WARNING
This chapter is written using a preview version of EF4, so final functionality may differ. It is also worth
noting that EF is likely to have releases out of band. For the examples in this chapter you will need to install the EF CTP 2.
EF and LINQ to SQL
Some developers are understandably confused by the overlap between EF and LINQ to SQL. EF and
LINQ to SQL were developed by two different teams—hence the overlap. LINQ to SQL is a great piece of
technology and very suitable as a simple, light-weight wrapper to SQL. It is pretty clear, however, that
Microsoft is pushing developers to use EF. This is a sensible (although no doubt irritating) move as LINQ
to SQL is fundamentally flawed as a generic ORM solution in that
• It only works with SQL Server.
• Generated classes must have a 1 to 1 relationship with database objects.
EF provides an abstraction above the database layer and a number of enhancements that make it
superior to LINQ to SQL.
Is LINQ to SQL Dead?
Er, probably not.
In October 2008 Microsoft’s Tim Mallalieu (Program Manager, LINQ to SQL and LINQ to Entities)
stated:
“We’re making significant investments in the Entity Framework such that as of .NET
4.0 the Entity Framework will be our recommended data access solution for LINQ to
relational scenarios.”
/>entities-roadmap.aspx


CHAPTER 8  ENTITY FRAMEWORK

176
However, after feedback from a large number of LINQ to SQL customers, Microsoft seemed to back
off on this a bit, when Tim said:
“We will continue make some investments in LINQ to SQL based on customer
feedback. This post was about making our intentions for future innovation clear and
to call out the fact that as of .NET 4.0, LINQ to Entities will be the recommended data
access solution for LINQ to relational scenarios “

on-l2s-futures.aspx
LINQ to SQL changes
In VS2010/.NET 4.0 LINQ to SQL has a number of welcome performance enhancements and bug fixes. It
is slightly troublesome that there is very little information on this at the time of writing, but for a full list
please see the blog post by Damien Guard (who works at Microsoft within the data programmability
team) at
Why Use EF?
The sections below cover the benefits of using an ORM solution, although please note that some of these
advantages are not EF specific—excellent (and more mature) alternatives do exist. Probably the best-
known and one of the most mature ORM in the .NET world is NHibernate. You can, however, view an
extensive list at
Abstraction
Data is generally held in a relational manner that is optimized for storage and quick retrieval (well, in
most cases it should be). However, this format tends to not map that easily to how we want to work with
objects. ORMs can provide a conceptual mapping that allows you to organize your entities and their
properties in a manner that is different than how they are physically stored.
For example, I worked on an application for a hospital that stored data about patients in two tables:
Person and Patient. These tables had a one-to-one relationship. Person held demographic details and
Patient held clinical-specific information. Whether this is the best database design is not important, but
you can probably see that when you want to work with a “patient,” it is tedious to have to work with two

separate objects. EF allows you to create an object that is spread across two tables, allowing you to write
more intuitive code, such as the following:

Patient.Firstname
Patient.BloodType
Code Generation
A great advantage of using an ORM solution is that it provides basic CRUD (created, read, update, delete)
functionality saving you from having to write this part. As code is automatically generated, the potential
for errors is also reduced. Using an ORM can also make it easier to adhere to naming conventions as
classes and methods are automatically generated.
CHAPTER 8  ENTITY FRAMEWORK

177
It is worth noting that by utilizing an ORM framework for data access, you are introducing
additional overhead to data access, and that for high performance applications, you may be better off
working with the database directly. Generally, however, the performance implications will probably be
pretty minimal and outweighed by the other advantages an ORM solution can bring.
Support for Different Databases
EF provides support for a number of different databases in addition to SQL Server, such as Oracle,
MySQL, SQLAnywhere, and, recently, Synergex’s Synergy and a few more.
EF contains its own query language and mechanisms that provide you with a consistent query
mechanism that can be used across many different data sources. EF doesn’t care whether your database
uses T-SQL or PL/SQL—querying is the same.
Design Time Support
EF has excellent design-time support that developers will quickly get to grips with. Yes, it was a bit ropey
in the original version, but this is much improved in VS2010. I don’t think the majority of ORMs provide
this level of GUI functionality, so this is definitely one of EF’s strengths.
Utilize LINQ
LINQ to Entities allows you to construct some very complex queries utilizing the .NET Framework that
would not be possible with standard SQL.

N-Tier Application Development
EF has a number of features (particularly in the latest release), such as support for POCO (Plain old CLR
object e.g.net classes!) and self-tracking of change templates, that make it a great solution for the
development of n-tier applications.
Where is EF Used?
Several areas of .NET 4.0 and VS2010 support or are dependent on EF:
• WCF Data Services
• Windows Azure
• Dynamic data framework
• Microsoft Ajax libraries
You can, of course, use EF anywhere in your application, but you may find it is particularly suitable
to some areas, such as:
• ASP.NET MVC
• Silverlight/WPF (many controls have inbuilt EF support)
• ASP.NET (many controls have built-in support for binding to EF objects)
CHAPTER 8  ENTITY FRAMEWORK

178
EF 101
Many developers may be unfamiliar with EF as it was released in between VS2008 and VS2010, or others
may have heard bad things about it (not all of which are true). Let’s take a quick look at how to work with
EF before looking at the new features in EF4.
Entity Data Model
All EF applications contain an entity data model (EDM) that describes the objects in the underlying data
source. The EDM can be further divided into three layers:
• Conceptual model (the view your users see)
• Storage model (how data is actually stored)
• Mapping model (links the conceptual and storage models)
EDMs are stored as XML and are composed of three main sections (which link to the three
conceptual layers already described):

• CSDL (Conceptual Schema Definition Language)
• SSDL (Store Schema Definition Language)
• MSL (Mapping Specification Language)
It is important to understand the format of the EDM file. EF contains good GUI support, but for
more advanced customizations it is necessary to modify the XML file directly. The exact format of your
EDM file is also dependent on how it is generated (described next).
If you generate your model using the wizard in Visual Studio, the EDM will be held in one file with
the extension .edmx with the conceptual, storage, and mapping sections split under the following nodes:
• edmx:StorageModels
• edmx:ConceptualModels
• edmx:Mappings
If, however, you generate your model using EDMGen.exe (discussed next) then the model will be split
into three separate files: .SSDL, .CSDL, and .MSL.
Creating an EDM
You can create an EDM in three different ways:
• The EDMGen command-line tool
• By using the ADO.NET data model wizard in Visual Studio
• By creating the model in Visual Studio and then having VS generate your database
structure from this model (new to EF4)
CHAPTER 8  ENTITY FRAMEWORK

179
EdmGen.exe
EdmGen.exe is a command-line tool primarily used for generating an EDM, but it also performs a number
of other tasks, such as verification of models and splitting generated files. You may want to utilize EdmGen
as part of your application's build process.
Creating an Entity Data Model in Visual Studio
The easiest way to create an EDM is by using the ADO.NET data model wizard in Visual Studio.
1. Open up Visual Studio.
2. Create a New C# Console application and call it Chapter8.HelloEF.

3. Right-click on the project and select AddNew Item.
4. Select ADO.NET Entity Data Model, and name it Chapter8Model.edmx (Figure 8-1).
5. Click Add.

Figure 8-1. Adding an ADO.NET Entity Data Model to our project
CHAPTER 8  ENTITY FRAMEWORK

180
6. The Choose Model Contents wizard screen will now appear (Figure 8-2). Select the "Generate
from database" option.

Figure 8-2. Generate from database
7. Click Next.
8. VS will now ask you for a connection (Figure 8-3). If you haven’t done this already, create a new
connection to the example database. Note that my database is called Book, so EF will prefix
many settings with the name of the database (you may wish to change this).
9. Click Next.
CHAPTER 8  ENTITY FRAMEWORK

181

Figure 8-3. Connection string properties
10. We now need to select the items in the database that we want EF to create entities for. Expand
the Tables node and select the following tables (Figure 8-4):
• Film
• FilmShowing
• Order
• OrderItem

NOTE

The wizard also allows you to create entities for views and stored procedures.
CHAPTER 8  ENTITY FRAMEWORK

182

Figure 8-4. Selecting items to generate EF classes for
11. Ensure that you have checked the “Pluralize or singularize generate object names” and "Include
foreign key columns in the model" (these are new options in EF—for more information please
refer to the following Pluralization section).
12. Set the model namespace as BookModel.
13. Click Finish. EF will then generate entities for the classes we have created and you will be taken
to the design view of the generated EF model (Figure 8-5).
CHAPTER 8  ENTITY FRAMEWORK

183

Figure 8-5. Design view of EF model
Notice how relationships between the entities have been automatically created. This is because our
database contained a number of constraints and relationships that were automatically imported into
our model. You can also create relationships yourself in the design view.
Navigating the EF model
When your EF model contains many entities then the designer window can get pretty crowded. You can
zoom in and out of the model view by clicking the magnifying icons in the corner of the scroll bars or by
right-clicking and selecting the zoom level.
Viewing How Entities Are Mapped
If you select one of the entities, then view the Mapping Details window, you will see how the individual
properties on the entity are mapped to the underlying database fields (Figure 8-6).
Now select one of the individual entity properties and Visual Studio will display information in the
Properties window, such as the type of field, length, and so on. Notice how you can also change the
name of the field and the getter and setter properties' access levels (Figure 8-7).


CHAPTER 8  ENTITY FRAMEWORK

184

Figure 8-6. EF Mapping window

Figure 8-7. Viewing the properties of
Film.Description

×