Entity Framework

16
1 Entity Framework Introduction

description

Entity Framework

Transcript of Entity Framework

Page 1: Entity Framework

1

Entity Framework Introduction

Page 2: Entity Framework

2

ORM’s 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)

Page 3: Entity Framework

Source: Gil Fink http://blogs.microsoft.co.il/blogs/gilf

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

3

Page 4: Entity Framework

Source: Jeff Derstadt

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

4

Page 5: Entity Framework

5Source: 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 dbms’es:

SQLServer

Oracle

MySQL

db2

Page 6: Entity Framework

6Source: Jeff Derstadt

Page 7: Entity Framework

Source: Jeff Derstadt

Getting Started

DB ModelCode

DB ModelCode

DB ModelCode

Design time

Design time

Design time

Design time

Runtime Runtime

Model First (VS 2010 and .NET 4.0)

Code First (Entity Framework Feature CTP3)

why? it already exists, or you want low level control over the database

why? you want separation from code and database in a declarative format

why? primarily focused on code shape, database is an implementation detail

7

Database First (VS 2008 and .NET 3.5 SP1)

Page 8: Entity Framework

8

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

Page 9: Entity Framework

9

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();

}

Page 10: Entity Framework

10

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…’

Page 11: Entity Framework

11

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.

Page 12: Entity Framework

12

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

Page 13: Entity Framework

13

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

Page 14: Entity Framework

14

Demo: Code FirstCreate 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

Page 15: Entity Framework

15

Demo: Code First (Dealing with Change in Code)

Let’s 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

Page 16: Entity Framework

16

Detailed Information

http://www.entityframeworktutorial.net/