ORM Technologies and Entity Framework (EF)

Slides:



Advertisements
Similar presentations
Introduction to NHibernate By Andrew Smith. The Basics Object Relation Mapper Maps POCOs to database tables Based on Java Hibernate. V stable Generates.
Advertisements

ADO.NET Entity Framework
Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Telerik Software Academy Telerik School Academy.
ORM Concepts, ADO.NET Entity Framework (EF), ObjectContext Doncho Minkov Telerik School Academy schoolacademy.telerik.com Technical Trainer
Entity Framework Code First End to End
BIT 286: Web Applications Lecture 04 : Thursday, January 15, 2015 ASP.Net MVC - Models.
C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins.
Using MongoDB with.NET Welcome to the JSON-stores world SoftUni Team Technical Trainers Software University
NHibernate in Action Web Seminar at UMLChina By Pierre Henri Kuaté 2008/08/27
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG.
NoSQL Databases NoSQL Concepts SoftUni Team Technical Trainers Software University
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
ORM Concepts, ADO.NET Entity Framework (EF), ObjectContext Doncho Minkov Telerik Corporation.
Database APIs and Wrappers
Entity Framework Performance SoftUni Team Technical Trainers Software University
Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects
ORM Concepts, Entity Framework (EF), DbContext
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Processing Redis with.NET How to Operate with Redis Databases SoftUni Team Technical Trainers Software University
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
ORM Technologies and Entity Framework (EF) ORM Concepts, Entity Framework, DbContext, CRUD Operations SoftUni Team Technical Trainers Software University.
Entity Framework: Code First SoftUni Team Technical Trainers Software University
Using SQL Connecting, Retrieving Data, Executing SQL Commands, … Svetlin Nakov Technical Trainer Software University
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer ORM Concepts, Entity Framework.
Processing JSON in.NET JSON, JSON.NET LINQ-to-JSON and JSON to XML SoftUni Team Technical Trainers Software University
Entity Framework Code First
Advanced C# Course Introduction SoftUni Team Technical Trainers Software University
ORM Basics Repository Pattern, Models, Entity Manager Ivan Yonkov Technical Trainer Software University
Entity Framework Database Connection with ASP Notes from started/getting-started-with-ef-using-mvc/creating-an-
Programming for Beginners Course Introduction SoftUni Team Technical Trainers Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Software Technologies Course Overview SoftUni Team Technical Trainers Software University
Programming Fundamentals Course Introduction SoftUni Team Technical Trainers Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Static Members Static Variables & Methods SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Entity Framework (EF) ORM and Entity Framework Code First. CRUD Operations SoftUni Team Technical Trainers Software University
Auto Mapping Objects SoftUni Team Database Applications
Working with Fluent API Inheritance Strategies
Introduction to Entity framework
Introduction to .NET Florin Olariu
Introduction to Entity Framework
ASP.NET Integration Testing
ASP.NET Unit Testing Unit Testing Web API SoftUni Team ASP.NET
EF Code First (Advanced)
EF Advanced Querying Optimize Performance SoftUni Team Advanced
EF Relations Object Composition
Entity Framework: Code First
Entity Framework DB From Code, OOP Introduction
Entity Framework: Relations
MVC Architecture, Symfony Framework for PHP Web Apps
Transactions in Entity Framework
C#: ASP.NET MVC Overview
Best Practices and Architecture
Best practices and architecture
Data Definition and Data Types
Entity Framework By: Casey Griffin.
Entity Framework Advanced Querying SoftUni Team Technical Trainers
ADO.NET Entity Framework
An Introduction to Entity Framework
C# - EF Core IT College, Andres Käver, , Fall semester
Presentation transcript:

ORM Technologies and Entity Framework (EF) Entity Framework, DbContext, CRUD Operations, Code First, Migrations Svetlin Nakov Inspiration Manager Software University http://softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Table of Contents ORM Technologies – Basic Concepts Entity Framework – Overview Database First with EF Reading Data and CRUD operations with EF Code First with EF Domain Classes and DbContext Migrations in EF © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

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

Relational database schema ORM Mapping – Example ORM Entities (C# classes) Relational database schema ORM Framework

Object-Relation Persistence Framework for .NET 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

EF: Basic Workflow Define the data model (use a DB visual designer or code first) Write & execute query over IQueryable EF generates & executes an SQL query in the DB

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

Database First with Entity Framework and Visual Studio Live Demo

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 © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Reading Data with LINQ Query We can also use extension methods for constructing the query Find element by id 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 using (var context = new SoftUniEntities()) { var project = context.Projects.Find(2); Console.WriteLine(project.Name); }

Creating New Data 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 var project = new Project() { Name = "Judge System", StartDate = new DateTime(2015, 4, 15) }; context.Projects.Add(order); context.SaveChanges(); Create a new project object Mark the object for inserting This will execute an SQL INSERT

Cascading Inserts 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 Employee employee = new Employee(); employee.FirstName = "Petya"; employee.LastName = "Grozdarska"; employee.Projects.Add(new Project { Name = "SoftUni Conf" } ); softUniEntities.Employees.Add(employee); softUniEntities.SaveChanges();

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 an SQL SELECT to load the first order This will execute an SQL UPDATE

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 deleting at the next save Employees employee = softUniEntities.Employees.First(); softUniEntities.Employees.Remove(employee); softUniEntities.SaveChanges(); This will execute the SQL DELETE command

Parameter placeholder 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 Return type Parameter value

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 Domain Classes DB EDMX Model

DbContext & ModelBuilder Code First in EF Domain classes DbContext & ModelBuilder DB Custom Configuration As needed © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

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

Domain Classes (Models) (2) Another example of domain class (model) 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

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

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(); © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

"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

Using Code First Migrations in EF Live Demo

ORM Technologies and Entity Framework (EF) https://softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

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 © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.