Sei sulla pagina 1di 8

Learning ADO.

NET Entity Framework


AuCnL1 LnLlLy lramework maps daLabase Lables Lo ob[ecLs
(http://www.dotnetcurry.com/ShowArticle.aspx?ID599)
The ADO.NET Entity Framework (EF) is an Object/Relational mapping (ORM) framework and is
a set of technologies in ADO.NET, for developing applications that interacts with data. We just
discussed that an ADO.NET developer spends a lot of time keeping up with the database
changes. Well EF provides a mapping from the relational database schema to the objects and
offers an abstraction of ADO.NET. So with EF, you can define Entity classes that are
independent of a database structure and then map them to the tables and associations of the
database. Since we are now working with Entities which have their own schema, we are
shielded from the changes in the database. The object context keeps tabs on the entities that
are changed.
In simple words, with the Entity Framework, you are architecting, designing and developing at
a conceptual level. You are no more worried about the `specific details of communicating with
the database and switching from one relational database to the other is also possible with EF,
without much efforts.
What happens to ADO.NET now?
ADO.NET is here to stay! EF was not released with the intension to replace ADO.NET. It is in
fact an enhancement to ADO.NET and helps eliminate the gap between the application and the
database. Behind the scene, EF uses ADO.NET classes, but the details are abstracted from
you. EF provides a shift from Database-oriented (DataReader, DataSet) to Model-oriented
development. So instead of focusing on a Database, a developer focuses on the Entity that
represents the Business Model of the application.
If the purpose of EF is not yet clear, it will be, in the forthcoming articles when we will explore
its features and look at it in detail. Continue reading as I am about to explain why EF was
chosen over LINQ To SQL!
When was Entity Framework Released?
Although announced in TechEd 2006, the first version of Entity Framework 3.5 was released
two years later in August 2008, along with Visual Studio 2008 SP1 and .NET 3.5 SP1.
The second version (also the current version) of Entity Framework i.e. 4.0 was released in
April 2010 along with VS 2010 and .NET 4.0.
What happened to LINQ To SQL?
When .NET 3.5 and Visual Studio 2008 was being released in November 2007, a lot of focus
was on LINQ. The original plan was to release EF along with VS 2008/.NET 3.5 and introduce
developers to this new LINQ based data access technology. However the scale of EF caused a
delay and it could not be released along with VS 2008.
Meanwhile, LINQ To SQL (L2S), worked upon by a different team at Microsoft was ready to
release. Since one of the focuses of the VS 2008 and .NET 3.5 release was on LINQ, it made a
lot of sense to release a LINQ Provider along with VS 2008. So during that time, L2S became
the original LINQ provider for data access. In my honest opinion, L2S was kind of a bait to
attract developers towards LINQ data access, while the team continued working on EF, i.e. the
real beast.
Finally when EF 3.5 was released in August 2008, it could not get the attention from the
developer community, for obvious reasons. L2S was gaining popularity primarily due to it
being lightweight, simple and easy to use technology and the fact that most of the .NET apps
targeted SQL Server, there was a resistance to adopt a new framework (EF) from the dev
community. EF remained a misunderstood technology, there were issues in the framework and
although accidental, L2S was still believed by many as the original LINQ provider for data
access. EF had a lot to prove!
However with the release of EF 4.0 with .NET 4.0, things have changed, including opinions.
Microsoft made it clear that although L2S was supported, it was not the recommended
technology. Moreover with the new features like POCO support, Model First Development and
Custom Code Generation, developers started looking at EF 4.0 and consider it seriously as the
preferred ORM solution for enterprise apps.
LINQ To SQL Vs Entity Framework
There are some fundamental differences between L2S and EF which every developer should
understand. Both EF and L2S provide a framework for managing relational data as objects,
with the objective of programming against a conceptual model rather than a DB schema.
However LINQ To SQL supports rapid development of applications that query only SQL Server
and SQL Server Compact 3.5 databases, providing a 1:1 mapping of your existing Database
schema to classes. It does not provide the flexibility to use objects that do not exactly match
the tables.
EF on the other hand, supports advanced modeling features and `loosely coupled and flexible
mapping of objects to SQL Server. Through extended ADO.NET Data Providers, EF supports
other relational databases as well, including Oracle, DB2, MySql etc. EF also allows objects to
have a different structure from your database schema.
Although LINQ To SQL (L2S) is supported by Microsoft, it is not recommended. Entity
Framework (EF) is definitely the way to go if you are working on something bigger (enterprise
apps), need the flexibility of a solid framework, with the support for multiple databases and
much more!
Note: LINQ to Entities is part of the Entity Framework and exposes many of the same features
as L2S. It has replaced L2S as the standard mechanism for using LINQ on databases.
How do I get Started with Entity Framework 4.0?
Well if you have continued reading so far, I assume you are interested in Entity Framework 4.0
and are ready to explore the future of data access. The easiest way to get started with it is to
download and install Visual Studio 2010.
The Entity Framework 4.0 is part of .NET 4.0, so both Visual Studio 2010 and the .NET 4.0
provide you with the necessary tools and technologies to begin developing. So you can either
download the Visual Studio 2010 Ultimate Trial Edition or get the free Visual Studio 2010
Express Edition.

+ Lxplorlng how Lhe LnLlLy uaLa Model (LuM) CeneraLes Code and LxecuLes Cuerles
hLLp//wwwdoLneLcurrycom/ShowArLlcleaspx?lu603
+ Learn by example
hLLp//wwwcodegurucom/csharp/csharp/neL30/arLlclephp/c13489__1/AuCnL1LnLlLylramework
1uLorlaland8aslcshLm
+ Cch Lro AuCnL1 LnLlLy uaLa Model brng Wlzard Addnew lLemuaLaAuCnL1 LnLlLy uaLa Model
Chu y Ln cra model dung dr lrp Lrlnh vl dr MyubLnLlLy dbConLexL new MyubLnLlLy()
+ vlrL rng drng Lruy xurL dr llru Lhm xa sra dr llru vrl AuCnL1 LnLlLy uaLa Model
ru dlrm vlrL rng drng vrl daLabase khng sr drng code nhlru
nhrrc dlrm Chra Lro AuCnL1 LnLlLy uaLa Model brng vlrL code phrl sr drng LlnCLoLnLlLles khng sr
drng drrc vrl csdl khc SCL Server (nru murn sr drng vrl daLabase khc phrl dung Lhm provlder cra
hng Lhr 3 hLLp//msdnmlcrosofLcom/enus/daLa/dd363363aspx)
Query an Entity from the Database (using LINQtoEntities):
norLhwlndLnLlLles dbConLexL new norLhwlndLnLlLles()
var query from p ln dbConLexLroducLSeL // var Cb[ecLCuery Cb[ecL8esulL or lCueryable
where pCaLegorlesCaLegoryname Seafood
selecL p
lLnumerableroducL producLs query1oLlsL()
Create and Add Objects in Entity Framework 4.0
In order to add new objects to the Entity Set, you must create an instance of an Entity type
and add the object to the object context. Objects attached to the object context are managed
by that object context. Now there are three ways to add a new object to the object context:
1. Use ObjectSet<TEntity>.AddObject()
2. Use ObjectContext.AddObject()
3. Use EntityCollection<TEntity>.Add()


All we are doing here is create a new instance of the Customer type and populate its
properties. We then add this instance to the Customers set using the
EntitySet<T>.AddObject method. The AddObject() method is used for adding newly
created objects that do not exist in the database. When AddObject() is called, a
temporary EntityKey is generated and the EntityState is set to 'Added', as shown
below:

When context.SaveChanges() is called, EF 4.0 goes ahead and inserts the record into the
database. Note that Entity Framework converts our code into queries that the database
understand and handles all data interaction and low-level details. Also notice in the code
above, that we are accessing data as objects and properties.
After you have executed the code, you can go ahead and physically verify the record in the
database. If the query executed successfully, you should see a new record in the Customers
table of the Northwind database
Lxample lnserL a new 8ecord ln Lhe uaLabase
norLhwlndLnLlLles dbConLexL new norLhwlndLnLlLles()
CaLegory caLegory new CaLegory()
caLegoryCaLegoryname 1esL CaLegory
roducL flrsLroducL new roducL()
flrsLroducLroducLname 1esL roducL 1
caLegoryroducLsAdd( flrsLroducL )
dbConLexLAdd1oCaLegorySeLcaLegory
dbConLexLSaveChanges()
Delete Objects in Entity Framework 4.0
To delete an existing record, retrieve an instance of the entity from the EntitySet<T>
(in our case ObjectSet<Customer>), then call the ObjectSet<TEntity>.DeleteObject()
. When the DeleteObject() method is called, the EntityState of the object is set to
`Deleted. Finally call SaveChanges() on the context to delete the data from the data
source. Another way to delete an object is to use the ObjectContext.DeleteObject()
but we have used the ObjectSet.DeleteObject for our example

Lxample ueleLe a 8ecord from Lhe uaLabase
norLhwlndLnLlLles dbConLexL new norLhwlndLnLlLles()
var query from p ln dbConLexLroducLSeL
where producLnameConLalns( 1esL )
selecL p
foreach ( roducL p ln query )
dbConLexLueleLeCb[ecL( p )
dbConLexLSaveChanges()
&pdate Objects in Entity Framework 4.0
As I mentioned earlier, objects attached to the object context are managed by that
object context. The steps to update an existing entity are quite simple. First retrieve
an instance of the entity from the EntitySet<T> (in our case ObjectSet<Customer>),
then edit the properties of the Entity and finally call SaveChanges() on the context.

Lxample updaLe an LnLlLy ln Lhe uaLabase
norLhwlndLnLlLles dbConLexL new norLhwlndLnLlLles()
roducL producL dbConLexLroducLSeLSlngle( p producLname Anlseed Syrup )
producLunlLrlce 1000
dbConLexLSaveChanges()

Create an Entity Framework Model and &se it in Multiple Projects (Tqo Entity
Framework Model trong m hnh da tng)
uung class llbrary pro[ecL Lrong m hlnh 3 Lrng Lhl Lro Lrong Lrng uaLa
Chu y MeLauaLa ArLlfacL rocesslng properLy
Double click to open the model and check its MetaData Artifact Processing property in
the Properties window, which is by default set to `Embed in Output Assembly, as
shown below

This property is very useful in scenarios where you want to use the use the model in
different projects. Since the model is created as a class library project (.dll), all you
need to do now is make a reference to the .dll in your project and supply the
connection string. The project using this model, finds the schema files (.csdl, .mls,
.ssdl) through the metadata property. Remember that all the schema files are
embedded into the .dll as resources. Open the App.config file and check the
connection string entry, which contains the schema files entries, as shown in the
screenshot below.

Note: If you are new to schema files, read my article Exploring how the Entity Data Model
(EDM) works.
You can now use this model in multiple projects like a Console Application, ASP.NET Project, a
Windows Forms project or a WPF Project. Make sure you have build the project (Go to Build >
Build MyEntityModel) and there are no errors.
&sing the Entity Model in a Console Application
We will now use the model we created above, in a Console Application.
Step 1: Open Visual Studio 2010 > File > New Project > In the templates, select Windows >
Console Application. Make sure the target framework is `.NET Framework 4.0. I have called
the application `ConsoleAppUsingMyModel. Click Ok.
Step 2: Let us now add a reference to the model we created earlier, in this console
application. Right click the project > Add Reference > Browse Projects Tab and browse to the
MyEntityModel project. Go to the 'bin' folder > Release and select the MyEntityModel.dll as
shown below. Click OK.


Also make sure you add a reference to the System.Data.Entity, this time using the .NET tab


Step 3: In this final step, our console application needs to have the information about the
connection string which contains the metadata and details of the database connection.
Note: If you skip this step and directly query the model, you will get an error The specified
named connection is either not found in the configuration, not intended to be used with the
EntityClient provider, or not valid.
Now you can either create your own .config file in this project and add the connectionstring
entry of your model or simply copy the App.config file that you created in the MyEntityModel
project, in your Console App project. We will adopt the simpler way. Right click the project >
Add Existing Item > Go to the MyEntityModel project and add the App.config file.
Step 4: Once the steps shown above are completed, you now need to query against the model
in order to fetch data. We will write code that displays the CustomerId and CompanyName of
customers who have placed orders after the 1st of January, 1998.
Open Program.cs and write the following query in your Main method






NguHn: bttp:JJwww.dotnetcurry.com, bttp:JJwww.codeguru.com

Potrebbero piacerti anche