* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download ORM Technologies and Entity Framework (EF)
Survey
Document related concepts
Extensible Storage Engine wikipedia , lookup
Oracle Database wikipedia , lookup
Navitaire Inc v Easyjet Airline Co. and BulletProof Technologies, Inc. wikipedia , lookup
Concurrency control wikipedia , lookup
Microsoft SQL Server wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Functional Database Model wikipedia , lookup
Open Database Connectivity wikipedia , lookup
ContactPoint wikipedia , lookup
Versant Object Database wikipedia , lookup
Relational model wikipedia , lookup
Transcript
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<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 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 Employees employee = softUniEntities.Employees.First(); Mark the entity for 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<string>( 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<PostAnswer>(); } Navigation property public virtual ICollection<PostAnswer> Answers { get; set; } public PostType Type { get; set; } Enumeration } 23 Defining the DbContext Class using System.Data.Entity; using CodeFirst.Models; Put all entity classes as DbSets 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; } } 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) ? 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