Entity Framework: Code First SoftUni Team Technical Trainers Software University

Slides:



Advertisements
Similar presentations
Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Advertisements

Telerik Software Academy Telerik School Academy.
ORM Technologies and Entity Framework (EF)
.NET Database Technologies: Entity Framework additional notes – part 2.
AngularJS Routing Routes, Route Parameters, Templates, Location, Navigation SoftUni Team Technical Trainers Software University
Using MongoDB with.NET Welcome to the JSON-stores world SoftUni Team Technical Trainers Software University
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Design Patterns: Structural Design Patterns
JavaScript Design Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers SoftUni.
NoSQL Databases NoSQL Concepts SoftUni Team Technical Trainers Software University
Composer packages Installing and Using Composer, Packagist, Packaging your code Mario Peshev Technical Trainer Software University
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
OVERVIEW ON HOW ENTITY FRAMEWORK CODE FIRST CAN EASE THE DEVELOPMENT PROCESS Entity Framework Code First 11/19/2013 Joe Walling Copyright Walling Info.
Database APIs and Wrappers
Entity Framework Performance SoftUni Team Technical Trainers Software University
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
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.
Controllers and Markup Controllers, $scope, Markup, Directives, Expressions, Binding, Filters, Validation SoftUni Team Technical Trainers Software University.
AMD and RequireJS Splitting JavaScript Code into Dependent Modules Software University Technical Trainers SoftUni Team.
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
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
JavaScript Modules and Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers.
Data Modeling Creating E/R Diagrams SoftUni Team Technical Trainers Software University
Processing JSON in.NET JSON, JSON.NET LINQ-to-JSON and JSON to XML SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Entity Framework Code First
Events Event Handling in JavaScript SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Working with Data Model Binders, Display Templates, Editor Templates, Validation… SoftUni Team Technical Trainers Software University
ASP.NET Identity System
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
ORM Basics Repository Pattern, Models, Entity Manager Ivan Yonkov Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Entity Framework Database Connection with ASP Notes from started/getting-started-with-ef-using-mvc/creating-an-
Sets, Dictionaries SoftUni Team Technical Trainers Software University
Рис.1. Схема взаємодії компонентів ASP.NET MVC Контролер (controller) - клас, з якого починається робота програми. Забезпечує зв'язок між моделлю і представленням.
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Web Storage and Cookies Cookies, Local and Session Storage SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Entity Framework (EF) ORM and Entity Framework Code First. CRUD Operations SoftUni Team Technical Trainers Software University
Working with Fluent API Inheritance Strategies
Introduction to Entity framework
Introduction to .NET Core and EF Core
Introduction to Entity Framework
ASP.NET Integration Testing
ASP.NET Unit Testing Unit Testing Web API SoftUni Team ASP.NET
Mocking tools for easier unit testing
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
Transactions in Entity Framework
Best Practices and Architecture
Best practices and architecture
Manual Mapping and AutoMapper Library
Entity Framework By: Casey Griffin.
Entity Framework Advanced Querying SoftUni Team Technical Trainers
IT College 2016, Andres käver
C# - EF Core IT College, Andres Käver, , Fall semester
Presentation transcript:

Entity Framework: Code First SoftUni Team Technical Trainers Software University

Table of Contents 1.EF Modelling Workflows 2.Code First Main Parts  Domain Classes (Models)  DbContext and DbSet  Database connection 3.Using Code First Migrations 4.Configuring Mappings 2

EF Modeling Workflows  EF supports three modeling workflows:  Database First  Create models from existing DB schema (DB  C# classes)  Model First  Create models in the EF designer in VS  Code First  Write models and combine them in DbContext (C# classes  DB) 3

4  Create models as database tables and then generate code (models) from them Database First Modeling Workflow DB EDMX Model EDMX Model Domain classes

5 Model First Modeling Workflow DB EDMX Model EDMX Model Domain classes

Code First Modeling Workflow Custom Configuration DbContext & ModelBuilder DbContext & ModelBuilder Domain classes As needed DB 6

Why Use Code First?  Write code without having to define mappings in XML or create database models  Define objects in POCO  Reuse these models and their attributes  No base classes required  Enables database persistence with no configuration  Can use automatic migrations  Can use data annotations ( Key, Required, etc.) 7

Code First Main Parts Domain Classes, DbContext and DbSet

Domain Classes (Models)  Bunch of normal C# classes (POCO)  May contain navigation properties  Recommended to be in a separate class library public class PostAnswer { public int PostAnswerId { get; set; } public int PostAnswerId { get; set; } public string Content { get; set; } public string Content { get; set; } public int PostId { get; set; } public int PostId { get; set; } public virtual Post Post { get; set; } public virtual Post Post { get; set; }} Primary key Foreign key Navigation property Virtual for lazy loading 9

10  Another example of domain class (model) Domain Classes (Models) (2) public class Post { private ICollection answers; private ICollection answers; public Post() public Post() { this.answers = new HashSet (); this.answers = new HashSet (); } public virtual ICollection Answers public virtual ICollection Answers { get { return this.answers; } get { return this.answers; } set { this.answers = value; } set { this.answers = value; } } public PostType Type { get; set; } public PostType Type { get; set; }} PreventsNullReferenceException Navigation property Enumeration

Creating Domain Classes (Models) Live Demo

12  A class that inherits from DbContext  Manages model classes using DbSet type  Implements identity tracking, change tracking  Provides API for CRUD operations and LINQ-based data access  Recommended to be in a separate class library  Don't forget to reference the Entity Framework library  Use the NuGet package manager  Use several DbContext if you have too much models The DbContext Class

DbSet Type  Collection of single entity type  Set operations: Add, Attach, Remove, Find  Use with DbContext to query database public DbSet Posts { get; set; } 13

14 Defining DbContext Class – Example using System.Data.Entity; using CodeFirst.Models; public class ForumContext : DbContext { public DbSet Categories { get; set; } public DbSet Categories { get; set; } public DbSet Posts { get; set; } public DbSet Posts { get; set; } public DbSet PostAnswers { get; set; } public DbSet PostAnswers { get; set; } public DbSet Tags { get; set; } public DbSet Tags { get; set; }}

Creating DbContext Live Demo

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

CRUD Operations with EF Code First Live Demo

18  Default App.config file contains link to default connection factory  Server name by default:  (localdb)\v11.0 or (localdb)\MSSQLLocalDB  We can use VS server explorer to view database Where is My Data? <entityFramework> </entityFramework>

19  First, create a context constructor that calls the base constructor with connection name  Then add the connection string in app.config How to Connect to SQL Server? public class ForumContext : DbContext { public ForumContext() : base("ForumDb") { … } public ForumContext() : base("ForumDb") { … } …} <connectionStrings> <add name="ForumDb" connectionString="Data Source=.; <add name="ForumDb" connectionString="Data Source=.; initial catalog=ForumDb;Integrated Security=True" initial catalog=ForumDb;Integrated Security=True" providerName="System.Data.SqlClient" /> providerName="System.Data.SqlClient" /></connectionStrings>

Database Connection Workflow Connection String Available? Build String (SQL Server Express or Create Local DB) Database Exists? Create Database Use Database No Yes No Yes 20

21  Connecting to LocalDB:  Connecting to LocalDB in Visual Studio

Change Database Connection Live Demo

Using Code EF First Migrations

24  What happens when we change our models?  Entity Framework compares our model with the model from the __MigrationHistory table in the DB  By default Entity Framework only creates the database  EF doesn't do any schema changes after that  Using Code First Migrations we can handle differences between models and database Changes in Domain Classes

25  Enable Code First Migrations  Open Package Manager Console  Run Enable-Migrations command  This will create some initial jumpstart code  -EnableAutomaticMigrations for auto migrations  Two types of migrations  Automatic migrations  Set AutomaticMigrationsEnabled = true;  Code-based (providing full control)  Separate C# code file for every migration Code First Migrations

26  CreateDatabaseIfNotExists  Default migration  DropCreateDatabaseIfModelChanges  We lose all the data when the model changes  DropCreateDatabaseAlways  Great for automated integration testing  MigrateDatabaseToLatestVersion  This option uses our migrations  Custom migrations  Implement IDatabaseInitializer for custom migration strategy Database Migration Strategies

27  First, enable code first migrations  Second, we need to tell to Entity Framework to use our migrations with code (or in App.config )  We can configure automatic migration Use Code First Migrations Database.SetInitializer( new MigrateDatabaseToLatestVersion ()); public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = true; this.AutomaticMigrationDataLossAllowed = true;} This will allow us to delete or change properties

28  During a migration we can seed the database with some data using the Seed() method  This method will be run after each migration Seeding the Database protected override void Seed(ForumContext context) { /* This method will be called after migrating to the latest version. /* This method will be called after migrating to the latest version. You can use the DbSet.AddOrUpdate() helper extension method You can use the DbSet.AddOrUpdate() helper extension method to avoid creating duplicate seed data. E.g. */ to avoid creating duplicate seed data. E.g. */ context.Tags.AddOrUpdate(t => t.Text, new Tag { Text = "C#" }); context.Tags.AddOrUpdate(t => t.Text, new Tag { Text = "C#" }); context.SaveChanges(); context.SaveChanges();}

Code First Migrations Live Demo

Configure Mappings Using Data Annotations and EF Fluent API

31  Entity Framework respects mapping details from two sources:  Data annotation attributes in the models  E.g. [Key], [Required], [MaxLength]  Can be reused for validation purposes  Fluent API code mapping configuration  By overriding OnModelCreating method  By using custom configuration classes  Use one approach or the other Configure Mappings

32  There is a bunch of data annotation attributes  System.ComponentModel.DataAnnotations  Specify the primary key of the table: [Key]  For validation:  [StringLength], [MaxLength], [MinLength], [Required]  Schema:  [Column], [Table], [ComplexType], [ConcurrencyCheck], [Timestamp], [InverseProperty], [ForeignKey], [DatabaseGenerated], [NotMapped], [Index]  EF 6 supports custom attributes by using custom conventions Data Annotations

Entity Framework Fluent API Using the ModelBuilder 33

EF Fluent API for Mappings  By overriding DbContext. OnModelCreating we can specify mapping configurations: protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity () modelBuilder.Entity ().HasKey(x => x.TagId);.HasKey(x => x.TagId); modelBuilder.Entity () modelBuilder.Entity ().Property(x => Text).IsUnicode(true);.Property(x => Text).IsUnicode(true); modelBuilder.Entity () modelBuilder.Entity ().Property(x => x.Text).HasMaxLength(255);.Property(x => x.Text).HasMaxLength(255); modelBuilder.Entity () modelBuilder.Entity ().Property(x => x.Text).IsFixedLength();.Property(x => x.Text).IsFixedLength(); base.OnModelCreating(modelBuilder); base.OnModelCreating(modelBuilder);} 34

35  When there several cascade delete paths, EF throws an exception  Two solutions with Fluent API:  Remove default cascade delete convention globally  Manually configure the relation Solving Cascade Delete Issue with Fluent API modelBuilder.Conventions.Remove ();.Remove (); modelBuilder.Entity<User>().HasMany(u => u.Answers).HasMany(u => u.Answers).WithRequired(a => a.User).WithRequired(a => a.User).WillCascadeOnDelete(false);.WillCascadeOnDelete(false);

36  When there several cascade delete paths, EF throws an exception  Two solutions with Fluent API:  Remove default cascade delete convention globally  Manually configure the relation Solving Cascade Delete Issue with Fluent API modelBuilder.Conventions.Remove ();.Remove (); modelBuilder.Entity<User>().HasMany(u => u.Answers).HasMany(u => u.Answers).WithRequired(a => a.User).WithRequired(a => a.User).WillCascadeOnDelete(false);.WillCascadeOnDelete(false);

37  In some cases EF does not properly recognize the relation  E.g. we want a User to have many friends (other users)  We have to manually map the relation to a many-to-many table Manually Setting Many-to-Many Relation modelBuilder.Entity<User>().HasMany(u => u.Friends).HasMany(u => u.Friends).WithMany().WithMany().Map(m =>.Map(m => { m.MapLeftKey("UserId"); m.MapLeftKey("UserId"); m.MapRightKey("FriendId"); m.MapRightKey("FriendId"); m.ToTable("UserFriends"); m.ToTable("UserFriends"); }); });

EF Fluent API Configurations .Entity()  Map: Table Name, Schema  Inheritance Hierarchies, Complex Types  Entity -> Multiple Tables  Table -> Multiple Entities  Specify Key (including Composite Keys) .Property()  Attributes (and Validation)  Map: Column Name, Type, Order  Relationships  Concurrency 38

EF: Configure Mappings Live Demo

? ? ? ? ? ? ? ? ? Entity Framework Code First

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 41  Attribution: this work may contain portions from  "Databases" course by Telerik Academy under CC-BY-NC-SA licenseDatabasesCC-BY-NC-SA

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg