ADO.NET Entity Framework Getting Started

auburnhairΛογισμικό & κατασκευή λογ/κού

13 Δεκ 2013 (πριν από 3 χρόνια και 4 μήνες)

133 εμφανίσεις

ADO.NET Entity Framework Getting
Started

Microsoft Corporation: Getting Started with the ADO.NET Entity Framework.

December
2007


The ADO.NET Entity Framework is scheduled to release
during the first half of 2008.

The ADO.NET Entity Framework provides a level of abstraction over a
data source
to
provid
e

an easier programming experience for developers that write data access
applications. The ADO.NET Entity Framework is based on the Entity Data Model
(EDM). Basically

the EDM allows users to model the database like the way they
designed the database in the first place, probably with an Entity
-
Relational (ER)
diagram.
This level of abstraction is important because as more and more application
information is being mainta
ined in the database, the relational schema more
frequently gets modified for performance and normalization.

Those changes can
affect the data access code in the application. For example, a product table may
become a join across a few tables, but as a prog
rammer I only really only care about
what the application defines as a Product entity. Just look at how the simple
Northwind model has transformed over the years to AdventureWorks.


Here’s a few links that may help later.

Data Programmability on MSDN

ADO.NET Team Blog

ADO.NET Entity Framework Beta 3

ADO.NET Entity Framework Tools CTP 2

Online documentation


What is LINQ to Entities?

There has been much discussion and numerous blog posts on LINQ, so we won’t
revisit

all the LINQ capabilities, but in a nut shell, LINQ provides a typed query
language. LINQ to Entities provides that same query capabilities over the ADO.NET
Entity Framework, as well as ORM functionality that users can now materialize their
Entities into
CLR types and program against the EDM and the database in a much
simpler fashion.

Let’s just step through some of the concepts with some code and visuals to help
explain better. I’ll point out advanced areas and tips to get you going. I’ll also point
out a
reas that we are working to improve.

The Data
Model

First, let’s start off with a database schema. Basically, I have a relational schema
that keeps track of travel blogs with friends, comments, and pictures. I’ll be using
this schema in future articles too
.


Figure 1

Database Schema

From the relational schema, step through the Add New Item wizard to add a new
ADO.NET Entity Data Model to any type of project in Visual Studio 2008.



Figure 2

Using the Wizard

The wizard creates a MyTravelPostModel.edmx

file that defines the EDM. The visual
Entity Designer enables you to do some renaming and fix up on my model to make
the programming experience better.




Figure 3

Using Entity Designer in Visual Studio

The wizard also generates the code need to program

against the model. Below is the
list of code generated classes.



Figure 4

The code generated results

There’s a one to one object type to the entity type you created in the model. In
addition to object types, a class called MyTravelEntities is also gener
ated. Inheriting
from ObjectContext, this class maintains the connection and metadata information
needed to read, write, update, and delete entities in the database. Also the
MyTravelEntities references a class called ObjectStateManager, which manages
chan
ge tracking and identity resolution. Basically if a query returns a Blog
entity, this
object is persisted during other query operations while

the context exists.

Getting at the
Data

Querying for Entities

Getting the data out is easy with a LINQ query.

C#

MyTravelEntities

travelEntities =
new

MyTravelEntities
();


var

travelBlogs =
from

tb
in

travelEntities.Blogs


where

tb.Person.Name ==
"Brian"


select

tb;



VB

Dim

travelEntities
As

New

MyTravelEntities


Dim

blogs =
From

tb
In

travelEntities.Blogs _


Where

tb.Person.Name =
"Brian"

_


Select

tb

Updating

the Entities

When you want to update the data, since the data is tracked by the
ObjectStateManager, the old and new values are kept so you can save t
he changes
back to the database.

C#

MyTravelEntities

travelEntities =
new

MyTravelEntities
();


Blog

blog = travelEntities.Blogs.First(b => b.Person.Name ==
"Brian"
);



blog.SeriesTitle =
"My second world trip"
;


travelEntities.SaveChanges();


VB

Dim

travelEntities
As

New

MyTravelEntities


Dim

firstBlog = (
From

tb
In

travelEntities.Blogs _


Where

tb.Person.Name =
"Brian"

_


Select

tb).Single()


firstBlog.SeriesTitle =
"The VB World Traveler"


travelEntities.SaveCh
anges()


Adding new Entities

Adding new entities is as easy as creating a new instance of an Entity object and
adding that to the ObjectContext. The code generated MyTravelEntities class includes
helper methods to easily add an entity to the correct
EntitySet, or table of types.

C#

MyTravelEntities

travelEntities =
new

MyTravelEntities
();


Person

newPerson =
new

Person
();

newPerson.Name =
"Jim"
;


travelEntities.AddToPeople(newPerson);


travelEntities.SaveChanges();



VB

Dim

travelEntities
As

New

MyTravelEntities


Dim

newPerson
As

New

Person

newPerson.Name =
"Jim"


travelEntities.AddToPeople(newPerson)


travelEntities.SaveChanges()


As a note, the Person entity has a PersonID property that you don’t need to set.

This is because the database gen
erates an identity value for this primary key
column, which before SaveChanges is called has a temporary value. After
SaveChanges is called, PersonID is updated with the server
-
generated key value.


Adding items that have relationships

When you add a pair
of related entities, you just need to the parent object and the
related object is added automatically.



C#

MyTravelEntities

travelEntities =
new

MyTravelEntities
();


Person

newPerson =
new

Person
();

newPerson.Name =
"Jim"
;


Blog

newBlog =
new

Blog
();

newBlog.SeriesTitle =
"My LINQ to Entities presentation travels"
;

newBlog.Person = newPerson;


travelEntities.AddToBlogs(newBlog);


travelEntities.SaveChanges();


VB

Dim

travelEntities
As

New

MyTravelEntities


Dim

newPerson
As

New

Person

newPerson.Name =
"Jim"


Dim

newBlog
As

New

Blog

newBlog.SeriesTitle =
"My LINQ to Entities presentation travels"

newBlog.Person = newPerson


travelEntities.AddToBlogs(newBlog)


travelEntities.SaveChanges()


Entity SQL and
Entity

Services

In addition to the other features explained in future posts, I wanted to point out
something about the ADO.NET Entity Framework. Below the LINQ to Entities
layer
is
an EntityClient provider layer that behaves like the SqlClient provider with a new
query la
nguage called Entity SQL. This gives you the flexibility to query against the
EDM without the materialization of CLR types.
You can also use Entity SQL within
Object Services for more ad

hoc query capabilities.

C#

EntityConnection

connection =
new

EntityCo
nnection
(connectionString);

connection.Open();


EntityCommand

command

=
new

EntityCommand
(
"SELECT blog FROM MyTravelEntities.Blogs "/


"as blog WHERE blog.Person.Name = 'Brian'"
,


connection);


DbDataReader

reader =
command.ExecuteReader(
CommandBehavior
.SequentialAccess);

while

(reader.Read())

{

// do something

}


VB

Dim

connection
As

New

EntityConnection

connection.ConnectionString = connectionString

connection.Open()


Dim

command
As

New

EntityCommand

command.CommandText =
"SELECT blog
FROM MyTravelEntities.Blogs as blog
WHERE blog.Person.Name = 'Brian'"

command.Connection = connection


Dim

reader = command.ExecuteReader(CommandBehavior.SequentialAccess)

While

(reader.Read())

' do something

End

While


Summary

LINQ to Entities in the ADO.NET Entity Framework provides a powerful programming
experience and several different layers. The top layer is the ORM layer, but if you
need to dive into the lower levels, you have those capabilities.

Hopefully these little co
de samples get you going with LINQ to Entities. Enjoy!