31
ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software University http:// softuni.bg

ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

Embed Size (px)

Citation preview

Page 1: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

ORM Technologies and Entity Framework (EF)

Entity Framework, DbContext, CRUD Operations, Code First, Migrations

Svetlin NakovInspiration ManagerSoftware Universityhttp://softuni.bg

Page 2: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

Table of Contents

1. ORM Technologies – Basic Concepts

2. Entity Framework – Overview

3. Database First with EF

4. Reading Data and CRUD operations with EF

5. Code First with EF Domain Classes and DbContext

6. Migrations in EF

2

Page 3: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

Introduction to ORM TechnologiesWhat is Object-Relational Mapping (ORM)?

Page 4: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

4

Object-Relational Mapping (ORM) is a programming technique for automatic mapping data and database schema Map relational DB tables to classes and objects

ORM creates a "virtual object database" Used from the programming language (C#, Java, PHP, …)

ORM frameworks automate the ORM process A.k.a. Object-Relational Persistence Frameworks

ORM Technologies

Page 5: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

5

ORM Mapping – Example

ORMFramework

Relational database schema

ORM Entities

(C# classes)

Page 6: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

Entity Framework (EF)Object-Relation Persistence Framework for .NET

Page 7: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

7

Entity Framework (EF) is the standard ORM framework for .NET Maps relational database to C# object model Powerful data manipulation API over the mapped schema CRUD operations and complex querying with LINQ

Database first approach: from database to C# classes Code first approach: from classes to DB schema Visual Studio generates EF data models

Data mappings consist of C# classes, attributes and XML

Overview of EF

Page 8: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

8

EF: Basic Workflow

2. Write & execute query over IQueryable

3. EF generates & executes an SQL query in the DB

1. Define the data model (use a DB visual designer or code first)

Page 9: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

9

EF: Basic Workflow (2)

5. Modify data with C# code and call "Save Changes"

6. Entity Framework generates & executes SQL command to modify the DB

4. EF transforms the queryresults into .NET objects

Page 10: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

Database First with EntityFramework and Visual Studio

Live Demo

Page 11: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

11

Entity Framework – Components

The DbContext class DbContext holds the DB connection Holds and DbSet<T> for the entity classes Provides LINQ-based data access ( through IQueryable) Provides API for CRUD operations

Entity classes Hold entities (objects with their attributes and relations) Each database table is typically mapped to a single C# entity class

Page 12: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

12

We can also use extension methods for constructing the query

Find element by id

Reading Data with LINQ Query

using (var context = new SoftUniEntities()){ var project = context.Projects.Find(2); Console.WriteLine(project.Name);}

using (var context = new SoftUniEntities()){ var employees = context.Employees .Select(c => c.FirstName) .Where(c => c.JobTitle == "Design Engineering") .ToList();}

This is called projection

ToList() method executes the SQL query

This is called selection

Page 13: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

13

To create a new database row use the method Add(…) of the corresponding collection:

SaveChanges() method executes the SQL insert / update / delete commands in the database

Creating New Data

var project = new Project(){ Name = "Judge System", StartDate = new DateTime(2015, 4, 15)};

context.Projects.Add(order);context.SaveChanges(); This will execute an SQL INSERT

Create a new project object

Mark the object for inserting

Page 14: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

14

We can also add cascading entities to the database:

This way we don't have to add Project individually They will be added when the Employee entity (employee) is

inserted to the database

Cascading Inserts

Employee employee = new Employee();employee.FirstName = "Petya";employee.LastName = "Grozdarska";employee.Projects.Add(new Project { Name = "SoftUni Conf" } ); softUniEntities.Employees.Add(employee);softUniEntities.SaveChanges();

Page 15: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

15

DbContext allows modifying entity properties and persisting them in the database Just load an entity, modify it and call SaveChanges()

The DbContext automatically tracks all changes made on its entity objects

Updating Existing Data

Employees employee = softUniEntities.Employees.First();employees.FirstName = "Alex";context.SaveChanges(); This will execute

an SQL UPDATE

This will execute an SQL SELECT to load

the first order

Page 16: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

16

Delete is done by Remove() on the specified entity collection SaveChanges() method performs the delete action in the

database

Deleting Existing Data

Employees employee = softUniEntities.Employees.First();

softUniEntities.Employees.Remove(employee);

softUniEntities.SaveChanges();

Mark the entity for deleting at the next save

This will execute the SQL DELETE command

Page 17: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

17

Native SQL Queries

var context = new SoftUniEntities();string nativeSQLQuery = "SELECT FirstName + ' ' + LastName " + "FROM dbo.Employees WHERE JobTitle = {0}";

var employees = context.Database.SqlQuery<string>( nativeSQLQuery, "Marketing Specialist");

foreach (var emp in employees){ Console.WriteLine(emp);}

Parameter placeholder

Parameter value

Return type

Page 18: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

CRUD Operations with EFLive Demo

Page 19: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

"Code First" Approach in EFFrom Classes to DB Schema

Page 20: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

20

Create database schema and generate C# code (models) from it

Database First in EF

DBEDMX Model

Domain Classes

Page 21: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

21

Code First in EF

Custom Configuration

DbContext & ModelBuilder

Domain classes

As needed

DB

Page 22: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

22

Domain Classes (Models)

Bunch of normal C# classes (POCO) May hold navigation properties

public class PostAnswer{ public int Id { get; set; } public string Content { get; set; } public int PostId { get; set; } public virtual Post Post { get; set; }}

Primary key

Foreign key

Navigation property

Virtual for lazy loading

Page 23: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

23

Another example of domain class (model)

Domain Classes (Models) (2)

public class Post{ public Post() { this.Answers = new HashSet<PostAnswer>(); }

public virtual ICollection<PostAnswer> Answers { get; set; } public PostType Type { get; set; }}

This prevents NullReferenceException

Navigation property

Enumeration

Page 24: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

24

Defining the DbContext Class

using System.Data.Entity;

using CodeFirst.Models;

public class ForumContext : DbContext{ public DbSet<Category> Categories { get; set; } public DbSet<Post> Posts { get; set; } public DbSet<PostAnswer> PostAnswers { get; set; } public DbSet<Tag> Tags { get; set; }}

Put all entity classes as DbSets

Page 25: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

25

CRUD Operations with EF Code First

var db = new ForumContext();

var category = new Category { Name = "Database course" };db.Categories.Add(category);

var post = new Post();post.Title = "Homework Deadline";post.Content = "Please extend the homework deadline";post.Type = PostType.Normal;post.Category = category;post.Tags.Add(new Tag { Text = "homework" });post.Tags.Add(new Tag { Text = "deadline" });

db.Posts.Add(post);

db.SaveChanges();

Page 26: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

"Code First" Approach in EFLive Demo

Page 27: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

Using Code First Migrations in EF

Page 28: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

28

Enable Code First Migrations Open Package Manager Console Run Enable-Migrations command

-EnableAutomaticMigrations for auto migrations

Code First Migrations in Entity Framework

Page 29: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

Using Code First Migrations in EFLive Demo

Page 31: ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education,

Profession and Job for Software Developers softuni.bg

Software University @ Facebook facebook.com/SoftwareUniversity

Software University @ YouTube youtube.com/SoftwareUniversity

Software University Forums – forum.softuni.bg