ORM Technologies and Entity Framework (EF)

ORM Technologies and Entity Framework (EF)

ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software University http://softuni.bg 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 Introduction to ORM Technologies What is Object-Relational Mapping (ORM)? ORM Technologies 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 4 ORM Mapping Example Relational database

schema ORM Framework ORM Entities (C# classes) 5 Entity Framework (EF) Object-Relation Persistence Framework for .NET

Overview of EF 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 7 EF: Basic Workflow 1. Define the data

model (use a DB visual designer or code first) 2. Write & execute query over IQueryable 3. EF generates & executes an SQL query in the DB 8

EF: Basic Workflow (2) 4. EF transforms the query results into .NET objects 5. Modify data with C# code and call "Save Changes" 6. Entity Framework generates & executes SQL

command to modify the DB 9 Database First with Entity Framework and Visual Studio Live Demo Entity Framework Components The DbContext class DbContext holds the DB connection Holds and DbSet 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 11 Reading Data with LINQ Query We can also use extension methods for constructing the query using (var context = new SoftUniEntities()) { var employees = context.Employees This is called projection .Select(c => c.FirstName)

.Where(c => c.JobTitle == "Design Engineering") .ToList(); This is called ToList() method } Find element by id executes the SQL query selection using (var context = new SoftUniEntities())

{ var project = context.Projects.Find(2); Console.WriteLine(project.Name); } 12 Creating New Data To create a new database row use the method Add() of the corresponding collection: var project = new Project() Create a new { project object Name = "Judge System",

StartDate = new DateTime(2015, 4, 15) }; Mark the object for inserting context.Projects.Add(order); context.SaveChanges(); This will execute an SQL INSERT SaveChanges() method executes the SQL insert / update / delete commands in the database 13

Cascading Inserts We can also add cascading entities to the database: Employee employee = new Employee(); employee.FirstName = "Petya"; employee.LastName = "Grozdarska"; employee.Projects.Add(new Project { Name = "SoftUni Conf" } ); softUniEntities.Employees.Add(employee); softUniEntities.SaveChanges(); This way we don't have to add Project individually They will be added when the Employee entity (employee) is

inserted to the database 14 Updating Existing Data 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 Employees employee = softUniEntities.Employees.First(); employees.FirstName = "Alex"; context.SaveChanges(); This will execute

This will execute an SQL SELECT to load the first order an SQL UPDATE 15 Deleting Existing Data Delete is done by Remove() on the specified entity collection SaveChanges() method performs the delete action in the database Mark the entity for Employees employee =

softUniEntities.Employees.First(); deleting at the next save softUniEntities.Employees.Remove(employee); softUniEntities.SaveChanges(); This will execute the SQL DELETE command 16 Native SQL Queries var context = new SoftUniEntities(); Parameter string nativeSQLQuery = placeholder "SELECT FirstName + ' ' + LastName " +

"FROM dbo.Employees WHERE JobTitle = {0}"; var employees = context.Database.SqlQuery( nativeSQLQuery, "Marketing Specialist"); foreach (var emp in employees) { Console.WriteLine(emp); } Parameter value Return type

17 CRUD Operations with EF Live Demo "Code First" Approach in EF From Classes to DB Schema Database First in EF Create database schema and generate C# code (models) from it DB EDMX Model

Domain Classes 20 Code First in EF DbContext & ModelBuilder Domain classes Custom

Configuration DB As needed 21 Domain Classes (Models) Bunch of normal C# classes (POCO) May hold navigation properties public class PostAnswer Primary key

{ public int Id { get; set; } public string Content { get; set; } Foreign key public int PostId { get; set; } public virtual Post Post { get; set; } } Navigation property Virtual for lazy loading 22 Domain Classes (Models) (2) Another example of domain class (model)

public class Post { This prevents public Post() NullReferenceException { this.Answers = new HashSet(); Navigation } property public virtual ICollection Answers { get; set; } Enumeration public PostType Type { get; set; } }

23 Defining the DbContext Class using System.Data.Entity; using CodeFirst.Models; Put all entity classes as DbSets public class ForumContext : DbContext { public DbSet Categories { get; set; } public DbSet Posts { get; set; } public DbSet PostAnswers { get;

set; } public DbSet Tags { get; set; } } 24 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(); 25 "Code First" Approach in EF Live Demo Using Code First Migrations in EF Code First Migrations in Entity Framework

Enable Code First Migrations Open Package Manager Console Run Enable-Migrations command -EnableAutomaticMigrations for auto migrations 28 Using Code First Migrations in EF Live Demo

ORM Technologies and Entity Framework (EF) ? Qu ? s n o ti s e

? ? ? ? ? ? ? ?

https://softuni.bg 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

Recently Viewed Presentations

  • Chapter 9: The Right to Keep and Bear Arms

    Chapter 9: The Right to Keep and Bear Arms

    Manslaughter does require the proof of the Corpus Delicti for homicide. Criminal Law- Manslaughter Voluntary manslaughter - an intentional killing of one human being by another, done in a sudden heat of passion, rage, or outrageous emotion- that has been...
  • Identity Cards: Strategy, Implementation & Challenges - UCL

    Identity Cards: Strategy, Implementation & Challenges - UCL

    Times Arial Monotype Corsiva Times New Roman Blank Identity Cards: Strategy, Implementation & Challenges A Melodrama in Three Parts PART 1 Why introduce a national ID system? What types of ID system are used?
  • TRAINING Professor Sir Brian Greenwood, London School of

    TRAINING Professor Sir Brian Greenwood, London School of

    OVERVIEW & EVIDENCE. 1.5 Medicines used in SMC. In clinical trials, SP+AQ gave greater protection than other drug combinations. The use of the two drugs incombination limits the risk for selection for resistance to either SP or AQ use as...
  • Making Sense of MLA Format - Weebly

    Making Sense of MLA Format - Weebly

    Making Sense of MLA Format Proper citation & styling for the study of English Why do I have to do this? Once upon a time in a boring land far, far away, the Powers That Be gathered atop Mount Finicky...
  • Ikonográfiai alapismeretek

    Ikonográfiai alapismeretek

    Ikonográfiai alapismeretek I. Alapfogalmak 2011. II. 17 MNHMOΣYNE Engram Acheiropoeton Εικών γραφειν eikón grafein Ikonográfiai alapismeretek I. Alapfogalmak 2011.
  • UNCLASSIFIED PAY AND ENTITLEMENTS UNCLASSIFIED Presenter: MSgt Thames

    UNCLASSIFIED PAY AND ENTITLEMENTS UNCLASSIFIED Presenter: MSgt Thames

    Submit a NAVMC 11116 via DTMS to have the DO/FO BAH-RC Q/R to BAH I. Checkages. must be reported for field duty. ANNUAL TRAINING AND ACTIVE DUTY OPERATIONAL SUPPORT (ADOS) 30 DAYS OR LESS. ... PowerPoint Presentation Last modified by:...
  • Soot Particle Aerosol Mass Spectrometer: Development, Validation, and

    Soot Particle Aerosol Mass Spectrometer: Development, Validation, and

    Diameter rBC ∼ 120 nm. Similar in size to diesel exhaust particulate emissions (fresh) Diameter organics ~ 170 nm. Consistent with coating effects. Sulfates indicator of the accumulation mode. Particles least affected by atmosphere (persistent) rBC from local sources
  • The surface of Mars, and why we want to go there

    The surface of Mars, and why we want to go there

    The surface of Mars, and why we want to go there A case of particular interest: Gusev crater Next time: the view from the surface More mysteries on Mars?