Sie sind auf Seite 1von 16

Entity Framework Introduction

ORMs provides a way to map


ORM is:
A programming technique for converting data between
incompatible type systems (such as DBMS) in
relational databases and object-oriented programming
languages.
It does the plumbing work for you to aggregate, modify
and save your data back to its storage in Object Oriented
manner (easy to understand, maintain and extend)

Entity Framework is also a ORM


Data access framework
Supports data-centric applications and services
EF uses a model called an Entity Data Model (EDM)
EDM is a client-side data model
EDM is an abstraction layer on top of the data storage
Remove the pain of
Interacting with the data storage
Translating the data into objects

Source: Gil Fink

Entity Framework in a Nutshell


Goal: Simple and seamless data access for the .NET
platform
Better layering
Better re-use of existing knowledge and assets
EDM Entity Data Model
An abstract model for defining entities and relationships
Entity Framework
An implementation of EDM and an ORM layer on top
A framework for using entities over data

Source: Jeff Derstadt

Data Store
The Entity Framework has no knowledge of the database
that stores the data
It connects and interacts with the database through a
provider that is usually declared in the configuration file
As in ADO.NET the providers are supplied by the dbms
vendors
Some supported dbmses:
SQLServer
Oracle
MySQL
db2

Source: Jeff Derstadt

Source: Jeff Derstadt

Getting Started
Database First
DB

DB

Design time

Code

why? it already exists,


or you want low level
control over the
database

(VS 2010 and .NET 4.0)

Design time

Code First
DB

Model

Design time

Model First

(VS 2008 and .NET 3.5 SP1)

Model

Design time

Code

why? you want


separation from code
and database in a
declarative format

(Entity Framework Feature CTP3)

Runtime

Model

Runtime

Source: Jeff Derstadt

Code

why? primarily focused


on code shape,
database is an
implementation detail
7

Demo: Database first


Existing DB (but for Demo create a DB Blogging using Server Explorer)
Use below script to create 2 Tables (Blogs and Posts)
CREATE TABLE [dbo].[Blogs] ( [BlogId] INT IDENTITY (1, 1) NOT NULL, [Name] NVARCHAR (200) NULL, [Url]
NVARCHAR (200) NULL, CONSTRAINT [PK_dbo.Blogs] PRIMARY KEY CLUSTERED ([BlogId] ASC) );
CREATE TABLE [dbo].[Posts] ( [PostId] INT IDENTITY (1, 1) NOT NULL, [Title] NVARCHAR (200) NULL,
[Content] NTEXT NULL, [BlogId] INT NOT NULL, CONSTRAINT [PK_dbo.Posts] PRIMARY KEY CLUSTERED
([PostId] ASC), CONSTRAINT [FK_dbo.Posts_dbo.Blogs_BlogId] FOREIGN KEY ([BlogId]) REFERENCES
[dbo].[Blogs] ([BlogId]) ON DELETE CASCADE );

Create a Console Application


Add Entity ADO.NET Model and choose to generate the model from
existing Database
Connect to the Existing Database you created and Check to select all dbo
elements you want to add to model

Demo: Database first


Generate code that uses the Dbcontext, Rightclick on Designer surface and
Select Add Code Generation Item.., Use EF 5.x DBContext Generator for C# in
Visual Studio
Add below code to access DB using EF
using (var db = new BloggingContext())
{
Console.Write("Enter a name for a new Blog: ");
var name = Console.ReadLine();
var blog = new Blog { Name = name };
db.Blogs.Add(blog);
db.SaveChanges();
var query = from b in db.Blogs orderby b.Name select b;
Console.WriteLine("All blogs in the database:");
foreach (var item in query)
{
Console.WriteLine(item.Name);
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}

Demo: Database first (Dealing with change in DB)


Lets add a new table in Database and see how to update our Model again
from DB
CREATE TABLE [dbo].[Users] ( [Username] NVARCHAR(50) NOT NULL PRIMARY KEY,
[DisplayName] NVARCHAR(MAX) NULL )

Right-click on EF Designer and select Update Model from Database

10

Demo: Model first


Create a Console Application
Create Model, Add Entity ADO.NET Model and choose to create a new
model BloggingModel
In the Properties window change the Entity Container Name to
BloggingContext
Add Entities Blog BlogId, Name, Url (Nullable)
Post PostId, Title, Content
Add Association One (Blog) to Many (Posts) between these entities
Now Model is ready -> Generate code, Rightclick on Designer surface and
Select Add Code Generation Item.., Use EF 5.x DBContext Generator for
C# in Visual Studio
Generate Database -> Right-click on the design surface and select
Generate Database from Model
Click New Connection enter ModelFirst.Blogging as the database name.

11

Demo: Model first


Entity Framework Designer will calculate a script to create the database
schema
Right-click on the script and select Execute
Add code to access DB using EF

12

Demo: Model first (Dealing with change in Model)


Add new entity User in the Model, User -> Username(string, max
length(50)), DisplayName
Update Database using Generate Database from Model , again script will
be created, execute script

13

Demo: Code First


Create a Console Application
Create Classes Blog and Post
public class Blog { public int BlogId { get; set; } public string Name { get; set; } public virtual List<Post> Posts
{ get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content {
get; set; }
public int BlogId { get; set; } public virtual Blog Blog { get; set; } }

Create a Context
using System.Data.Entity;
public class BloggingContext : DbContext {
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}

Add code to access read and write objects of classes define


Execute your application
DbContext has created a database for you with fully qualified name of the
derived context

14

Demo: Code First (Dealing with Change in Code)


Lets add a User class to our model
public class User {
public string Username { get; set; }
public string DisplayName { get; set; }
}

Add a set to our derived context


To do changes, we need to enable migrations
Package Manager Console -> Enable-Migrations
Creates Configuration.cs (settings to be used for migration)
<timestamp>_InitialCreate.cs (first migration or initial code state)
Add-Migration AddUser (scaffolds code for new migration or change)
Update-Database
Throws error as No Primary Key for User defined
Data Annotation using System.ComponentModel.DataAnnotations;
Add [Key] attribute to the Key field and repeat for migrating

15

Detailed Information
http://www.entityframeworktutorial.net/

16

Das könnte Ihnen auch gefallen