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

Slides:



Advertisements
Similar presentations
Windows Basic and Dynamic Disk Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator Marian Marinov CEO of 1H Ltd.
Advertisements

Amazon S 3, App Engine Blobstore, Google Cloud Storage, Azure Blobs Svetlin Nakov Telerik Software Academy academy.telerik.com.
RPN and Shunting-yard algorithm Ivaylo Kenov Telerik Software Academy academy.telerik.com Technical Assistant
Telerik School Academy ASP.NET MVC.
Shortest paths in edge-weighted digraph Krasin Georgiev Technical University of Sofia g.krasin at gmail com Assistant Professor.
Telerik Software Academy Telerik School Academy.
Asynchronous Programming with C# and WinRT
Unleash the Power of JavaScript Tooling Telerik Software Academy End-to-end JavaScript Applications.
Telerik Software Academy Telerik School Academy.
Telerik School Academy ASP.NET MVC.
Character sequences, C-strings and the C++ String class, Working with Strings Learning & Development Team Telerik Software Academy.
Hybrid or Native?! Doncho Minkov Telerik Software Academy Senior Technical Trainer
Done already for your convenience! Telerik School Academy Unity 2D Game Development.
C# Fundamentals – Part I
ORM Technologies and Entity Framework (EF)
NoSQL Concepts, Redis, MongoDB, CouchDB
Telerik Software Academy Telerik School Academy Creating E/R Diagrams with SQL Server.
The Business Plan and the Business Model Margarita Antonova Volunteer Telerik Academy academy.telerik.com Business System Analyst Telerik Corporation.
What are ADTs, STL Intro, vector, list, queue, stack Learning & Development Team Telerik Software Academy.
Making JavaScript code by template! Learning & Development Team Telerik Software Academy.
Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training Who, What, Why?
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Processing Matrices and Multidimensional Tables Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Learning & Development Telerik Software Academy.
Reading and Writing Text Files Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Telerik Software Academy ASP.NET Web Forms.
Classical OOP in JavaScript Classes and stuff Telerik Software Academy
Using Selenium for Mobile Web Testing Powered by KendoUI Telerik QA Academy Atanas Georgiev Senior QA Engineer KendoUI Team.
NoSQL Concepts, Redis, MongoDB, CouchDB Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
New features: classes, generators, iterators, etc. Telerik Academy Plus JavaScript.Next.
Creating E/R Diagrams with SQL Server Management Studio and MySQL Workbench Svetlin Nakov Telerik Software Academy Manager Technical.
Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy
Private/Public fields, Module, Revealing Module Learning & Development Team Telerik Software Academy.
Building Data-Driven ASP.NET Web Forms Apps Telerik Software Academy ASP.NET Web Forms.
Course Introduction Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Nikolay Kostov Telerik Software Academy Senior Software Developer and Trainer
Telerik Software Academy End-to-end JavaScript Applications.
Planning and Tracking Software Quality Yordan Dimitrov Telerik Corporation Team Leader, Team Pulse, Team Leader, Team Pulse, Telerik Corporation,
What you need to know Ivaylo Kenov Telerik Corporation Telerik Academy Student.
Data binding concepts, Bindings in WinJS George Georgiev Telerik Software Academy academy.telerik.com Technical Trainer itgeorge.net.
Pavel Kolev Telerik Software Academy Senior.Net Developer and Trainer
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
OVERVIEW ON HOW ENTITY FRAMEWORK CODE FIRST CAN EASE THE DEVELOPMENT PROCESS Entity Framework Code First 11/19/2013 Joe Walling Copyright Walling Info.
ORM Concepts, Entity Framework (EF), DbContext
When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Doing the Canvas the "easy way"! Learning & Development Telerik Software Academy.
Entity Framework: Code First SoftUni Team Technical Trainers Software University
Creating and Running Your First C# Program Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Correctly Formatting the Source Code Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
Processing Sequences of Elements Telerik Software Academy C# Fundamentals – Part 2.
Telerik JavaScript Framework Telerik Software Academy Hybrid Mobile Applications.
Building Rock-Solid Software Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Telerik Software Academy Databases.
Entity Framework Code First
Things start to get serious Telerik Software Academy JavaScript OOP.
Learning & Development Mobile apps for iPhone & iPad.
Processing Matrices and Multidimensional Tables Telerik Software Academy C# Fundamentals – Part 2.
Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
Implementing Control Logic in C# Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical trainer
Inheritance, Abstraction, Encapsulation, Polymorphism Telerik Software Academy Mobile apps for iPhone & iPad.
Mocking tools for easier unit testing Telerik Software Academy High Quality Code.
What why and how? Telerik School Academy Unity 2D Game Development.
Windows Security Model Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator
EF Code First (Advanced)
Entity Framework: Code First
Entity Framework DB From Code, OOP Introduction
Presentation transcript:

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

 Modeling Workflow  Code First Main Parts  Domain Classes (Models)  DbContext and DbSets  Database connection  Entity Framework Power Tools  Using Code First Migrations  Configure Mappings  Data Annotations and Fluent API 2

 Entity Framework supports three types of modeling workflow:  Database first  Create models as database tables  Use Management Studio or native SQL queries  Model first  Create models using visual EF designer in VS  Code first  Write models and combine them in DbContext 3

 Create models as database tables and then generate code (models) from them 4

5

Domain classes 6 Custom Configuration DbContext ModelBuilder As needed

 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

Domain classes, DbContext and DbSets

 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; }} Navigation property Foreign key Primary key Virtual for lazy loading 9

 Another example of domain class (model) 10 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; }} Navigation property Enumeration Prevents null reference exception

Creating domain classes (models)

 A class that inherits from DbContext  Manages model classes using DbSet type  Implements identity tracking, change tracking, and API for CRUD operations  Provides LINQ-based data access  Recommended to be in a separate class library  Don't forget to reference the Entity Framework library (using NuGet package manager)  If you have a lot of models it is recommended to use more than one DbContext 12

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

14 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; }}

 In the same way as when we use database first or model first approach 16 var db = new ForumContext(); var category = new Category { Parent = null, Name = "Database course", }; db.Categories.Add(category); var post = new Post(); post.Title = "Срока на домашните"; post.Content = "Моля удължете срока на домашните"; post.Type = PostType.Normal; post.Category = category; post.Tags.Add(new Tag { Text = "домашни" }); post.Tags.Add(new Tag { Text = "срок" }); db.Posts.Add(post);db.SaveChanges();

 By default app.config file contains link to default connection factory that creates local db  Server name by default: (localdb)\v11.0 or.\SQLEXPRESS.[full-class-name]  We can use VS server explorer to view database 18 <entityFramework> </entityFramework>

 First, create context constructor that calls base constructor with appropriate connection name 19 public class ForumContext : DbContext { public ForumContext() public ForumContext() : base("ForumDb") : base("ForumDb") { } { } //... //...} <connectionStrings> </connectionStrings>  Then add the connection string in app.config Server address might be.\SQLEXPRESS

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

 Very useful Visual Studio extension  Can generate entity data model from code first DbContext  Can generate code first models and context from existing database  Will be included by default in Visual Studio

 What happens when we change our models?  Entity Framework compares our model with the model in __MigrationHistory table  By default Entity Framework only creates the database and don't do any changes after that  Using Code First Migrations we can manage differences between models and database 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 26

 CreateDatabaseIfNotExists (default)  DropCreateDatabaseIfModelChanges  We loose all the data when change the model  DropCreateDatabaseAlways  Great for automated integration testing  MigrateDatabaseToLatestVersion  This option uses our migrations  We can implement IDatabaseInitializer if we want custom migration strategy 27

 First, enable code first migrations  Second, we need to tell to Entity Framework to use our migrations with code (or app.config)  We can configure automatic migration 28 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

 During a migration we can seed the database with some data using the Seed method  This method will be run every time (since EF 5) 29 protected override void Seed(ForumContext context) { /* This method will be called after migrating to /* This method will be called after migrating to the latest version. You can use the the latest version. You can use the DbSet.AddOrUpdate() helper extension method DbSet.AddOrUpdate() helper extension method to avoid creating duplicate seed data. E.g. */ to avoid creating duplicate seed data. E.g. */ context.Tags.AddOrUpdate(new Tag { Text = "срок" }); context.Tags.AddOrUpdate(new Tag { Text = "срок" }); context.Tags.AddOrUpdate(new Tag { Text = "форум" }); context.Tags.AddOrUpdate(new Tag { Text = "форум" });}

Using Data Annotations and Fluent API

 Entity Framework respects mapping details from two sources  Data annotation attributes in the models  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 32

 There is a bunch of data annotation attributes in System.ComponentModel.DataAnnotations  [Key] – specifies the primary key of the table  For validation: [StringLength], [MaxLength], [MinLength], [Required]  Schema: [Column], [Table], [ComplexType], [ConcurrencyCheck], [Timestamp], [ComplexType], [InverseProperty], [ForeignKey], [DatabaseGenerated], [NotMapped]  In EF 6 we will be able to add custom attributes by using custom conventions 33

 By overriding OnModelCreating method in DbContext class we can specify mapping configurations 34 protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity ().HasKey(x => x.TagId); modelBuilder.Entity ().HasKey(x => x.TagId); modelBuilder.Entity ().Property(x => x.Text).IsUnicode(true); modelBuilder.Entity ().Property(x => x.Text).IsUnicode(true); modelBuilder.Entity ().Property(x => x.Text).HasMaxLength(255); modelBuilder.Entity ().Property(x => x.Text).HasMaxLength(255); // modelBuilder.Entity ().Property(x => x.Text).IsFixedLength(); // modelBuilder.Entity ().Property(x => x.Text).IsFixedLength(); base.OnModelCreating(modelBuilder); base.OnModelCreating(modelBuilder);}

.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 35

форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране

1. Using c0de first approach, create database for student system with the following tables:  Students (with Id, Name, Number, etc.)  Courses (Name, Description, Materials, etc.)  StudentsInCourses (many-to-many relationship)  Homework (one-to-many relationship with students and courses), fields: Content, TimeSent  Annotate the data models with the appropriate attributes and enable code first migrations 2. Write a console application that uses the data 3. Seed the data with random values 38

 C# Telerik Academy  csharpfundamentals.telerik.com csharpfundamentals.telerik.com  Telerik Software Academy  academy.telerik.com academy.telerik.com  Telerik Facebook  facebook.com/TelerikAcademy facebook.com/TelerikAcademy  Telerik Software Academy Forums  forums.academy.telerik.com forums.academy.telerik.com 39