Entity Framework
Total Page:16
File Type:pdf, Size:1020Kb
Entity Framework #entity- framework Table of Contents About 1 Chapter 1: Getting started with Entity Framework 2 Remarks 2 Versions 2 Examples 2 Using Entity Framework from C# (Code First) 2 Installing The Entity Framework NuGet Package 3 What is Entity Framework ? 7 Chapter 2: .t4 templates in entity-framework 9 Examples 9 Dynamically adding Interfaces to model 9 Adding XML Documentation to Entity Classes 9 Chapter 3: Advanced mapping scenarios: entity splitting, table splitting 11 Introduction 11 Examples 11 Entity splitting 11 Table splitting 12 Chapter 4: Best Practices For Entity Framework (Simple & Professional) 14 Introduction 14 Examples 14 1- Entity Framework @ Data layer (Basics) 14 2- Entity Framework @ Business layer 18 3- Using Business layer @ Presentation layer (MVC) 21 4- Entity Framework @ Unit Test Layer 22 Chapter 5: Code First - Fluent API 26 Remarks 26 Examples 26 Mapping models 26 Step one: Create model. 26 Step two: Create mapper class 26 Step three: Add mapping class to configurations. 28 Primary Key 28 Composite Primary Key 28 Maximum Length 29 Required properties (NOT NULL) 29 Explict Foreign Key naming 30 Chapter 6: Code First Conventions 31 Remarks 31 Examples 31 Primary Key Convention 31 Removing Conventions 31 Type Discovery 31 DecimalPropertyConvention 33 Relationship Convention 34 Foreign Key Convention 35 Chapter 7: Code First DataAnnotations 37 Remarks 37 Examples 37 [Key] attribute 37 [Required] attribute 38 [MaxLength] and [MinLength] attributes 38 [Range(min,max)] attribute 39 [DatabaseGenerated] attribute 40 [NotMapped] attribute 41 [Table] attribute 42 [Column] attribute 42 [Index] attribute 43 [ForeignKey(string)] attribute 43 [StringLength(int)] attribute 44 [Timestamp] attribute 45 [ConcurrencyCheck] Attribute 45 [InverseProperty(string)] attribute 46 [ComplexType] attribute 47 Chapter 8: Complex Types 48 Examples 48 Code First Complex Types 48 Chapter 9: Database first model generation 49 Examples 49 Generating model from database 49 Adding data annotations to the generated model 50 Chapter 10: Database Initialisers 53 Examples 53 CreateDatabaseIfNotExists 53 DropCreateDatabaseIfModelChanges 53 DropCreateDatabaseAlways 53 Custom database initializer 53 MigrateDatabaseToLatestVersion 54 Chapter 11: Entity Framework Code First 55 Examples 55 Connect to an existing database 55 Chapter 12: Entity Framework with SQLite 57 Introduction 57 Examples 57 Setting up a project to use Entity Framework with an SQLite provider 57 Install SQLite Managed Libraries 57 Including Unmanaged Library 58 Editing the project's App.config 58 Required Fixes 58 Add SQLite connection string 59 Your first SQLite DbContext 59 Chapter 13: Entity-Framework with Postgresql 60 Examples 60 Pre-Steps needed in order to use Entity Framework 6.1.3 with PostgresSql using Npgsqlddexp 60 Chapter 14: Entity-framework Code First Migrations 61 Examples 61 Enable Migrations 61 Add your first migration 61 Seeding Data during migrations 63 Using Sql() during migrations 64 Other Usage 65 Doing "Update-Database" within your code 65 Initial Entity Framework Code First Migration Step by Step 66 Chapter 15: Inheritance with EntityFramework (Code First) 67 Examples 67 Table per hierarchy 67 Table per type 68 Chapter 16: Loading related entities 70 Remarks 70 Examples 70 Lazy loading 70 Eager loading 71 Strongly typed. 71 String overload. 71 Explicit loading 72 Filter related entities. 72 Projection Queries 72 Chapter 17: Managing entity state 74 Remarks 74 Examples 74 Setting state Added of a single entity 74 Setting state Added of an object graph 74 Example 75 Chapter 18: Mapping relationship with Entity Framework Code First: One-to-many and Many-to 76 Introduction 76 Examples 76 Mapping one-to-many 76 Mapping one-to-many: against the convention 77 Mapping zero or one-to-many 79 Many-to-many 79 Many-to-many: customizing the join table 80 Many-to-many: custom join entity 82 Chapter 19: Mapping relationship with Entity Framework Code First: One-to-one and variatio 85 Introduction 85 Examples 85 Mapping one-to-zero or one 85 Mapping one-to-one 89 Mapping one or zero-to-one or zero 89 Chapter 20: Model Restraints 91 Examples 91 One-to-many relationships 91 Chapter 21: Optimization Techniques in EF 93 Examples 93 Using AsNoTracking 93 Loading Only Required Data 93 Execute queries in the database when possible, not in memory. 94 Execute multiple queries async and in parallel 94 Bad Example 94 Good Example 95 Disable change tracking and proxy generation 95 Working with stub entities 96 Chapter 22: Tracking vs. No-Tracking 98 Remarks 98 Examples 98 Tracking queries 98 No-tracking queries 98 Tracking and projections 99 Chapter 23: Transactions 100 Examples 100 Database.BeginTransaction() 100 Credits 101 About You can share this PDF with anyone you feel could benefit from it, downloaded the latest version from: entity-framework It is an unofficial and free Entity Framework ebook created for educational purposes. All the content is extracted from Stack Overflow Documentation, which is written by many hardworking individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official Entity Framework. The content is released under Creative Commons BY-SA, and the list of contributors to each chapter are provided in the credits section at the end of this book. Images may be copyright of their respective owners unless otherwise specified. All trademarks and registered trademarks are the property of their respective company owners. Use the content presented in this book at your own risk; it is not guaranteed to be correct nor accurate, please send your feedback and corrections to [email protected] https://riptutorial.com/ 1 Chapter 1: Getting started with Entity Framework Remarks Entity Framework (EF) is an object-relational mapper (ORM) that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data- access code that developers usually need to write. Entity Framework allows you to create a model by writing code or using boxes and lines in the EF Designer. Both of these approaches can be used to target an existing database or create a new database. Entity Framework is the main ORM that Microsoft provides for the .NET Framework and Microsoft’s recommended data access technology. Versions Version Release Date 1.0 2008-08-11 4.0 2010-04-12 4.1 2011-04-12 4.1 Update 1 2011-07-25 4.3.1 2012-02-29 5.0 2012-08-11 6.0 2013-10-17 6.1 2014-03-17 Core 1.0 2016-06-27 Release Notes: https://msdn.microsoft.com/en-ca/data/jj574253.aspx Examples Using Entity Framework from C# (Code First) https://riptutorial.com/ 2 Code first allows you to create your entities (classes) without using a GUI designer or a .edmx file. It is named Code first, because you can create your models first and Entity framework will create database according to mappings for you automatically. Or you can also use this approach with existing database, which is called code first with existing database For example, if you want a table to hold a list of planets: public class Planet { public string Name { get; set; } public decimal AverageDistanceFromSun { get; set; } } Now create your context which is the bridge between your entity classes and the database. Give it one or more DbSet<> properties: using System.Data.Entity; public class PlanetContext : DbContext { public DbSet<Planet> Planets { get; set; } } We can use this by doing the following: using(var context = new PlanetContext()) { var jupiter = new Planet { Name = "Jupiter", AverageDistanceFromSun = 778.5 }; context.Planets.Add(jupiter); context.SaveChanges(); } In this example we create a new Planet with the Name property with the value of "Jupiter" and the AverageDistanceFromSun property with the value of 778.5 We can then add this Planet to the context by using the DbSet's Add() method and commit our changes to the database by using the SaveChanges() method. Or we can retrieve rows from the database: using(var context = new PlanetContext()) { var jupiter = context.Planets.Single(p => p.Name == "Jupiter"); Console.WriteLine($"Jupiter is {jupiter.AverageDistanceFromSun} million km from the sun."); } Installing The Entity Framework NuGet Package https://riptutorial.com/ 3 In your Visual Studio open the Solution Explorer window then right click on your project then choose Manage NuGet Packages from the menu: In the window that opens type EntityFramework in the search box in the top right. https://riptutorial.com/ 4 Or if you are using Visual Studio 2015 you'll see something like this: https://riptutorial.com/ 5 Then click Install. We can also install entity framework using the package manager console. To do you have first to open it using the Tools menu -> NuGet Package Manager -> Package Manager Console then enter this: Install-Package EntityFramework https://riptutorial.com/ 6 This will install Entity Framework and automatically add a reference to the assembly in your project. What is Entity Framework ? Writing and managing ADO.Net code for data access is a tedious and monotonous job. Microsoft has provided an O/RM framework called "Entity Framework" to automate database related activities for your application. Entity framework is an Object/Relational Mapping (O/RM) framework. It is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database. What is O/RM? ORM is a tool for storing data from domain objects to the relational database like MS SQL Server, in an automated way, without much programming. O/RM includes three main parts: 1. Domain class objects 2. Relational database objects 3. Mapping information on how domain objects map to relational database objects(e.x tables, views & stored procedures) ORM allows us to keep our database design separate from our domain class design. This makes the application maintainable and extendable. It also automates standard CRUD operation (Create, https://riptutorial.com/ 7 Read, Update & Delete) so that the developer doesn't need to write it manually.