Entity Framework Tutorials

 

bFirst vs CodeFirst Approach:-

·         DatabaseFirst approach can be used only with existing database  while CodeFirst approach can be used with existing database and a non existing or empty database.

·         CodeFirst used Migration tool for updates the database schema while DbFirst not used Migration.

 

Step To Add Existing Database In CodeFirst

·         FirstStep:-       Select CodeFirstFromDatabase from Entity DataModel Wizard

·         SecondStep:-   Run Enable-Migrations Command

·         Third Step:-     Run Add-Migration InitialModel -IgnoreChanges

·         Fourth Step:-   Run Update-Database

·         Now everytihing will same as CodeFirstWithNewDatabase   

 

 

What is ORM?

An object-relational mapper (ORM) performs the conversion between objects and relational database entities. It understands certain strategies for mapping tables to

objects and vice versa. It also converts programming language data types such as

strings and integers to and from database types like VARCHAR and Blob. Complex

ORMs handle things like database functions, stored procedures, and mapping object

hierarchies to tables.

 

Dapper/PetaPoco

Stack Overflow and the rest of Stack Exchange are powered by a custom ORM library

called Dapper. Dapper is considered a micro-ORM because it doesn’t write SQL queries

for you like many full-featured ORMs. It only tries to simplify the process of converting

between objects and relational data.

 

 

The drawback of a micro-ORM

You’ve seen how easy it is to use Dapper. It saves you from a lot of boilerplate code and

maintains great performance. Depending on your application, however, there’s a

drawback to using Dapper—and micro-ORMs in general. The problem is that you’re

writing SQL in your application code, and SQL isn’t standardized.

SQL isn’t the same for every database. SQLite will have different syntax and capabilities

than SQL Server and PostgreSQL.

 

Entity Framework:- ADO.NET Entity Framework is an ORM framework that empowers developers to work with various relational databases like SQL Server, Oracle, DB2, MYSQL etc. It allows developers to deal with data as objects or entities. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects using C# or VB.NET Framework.

 

Entity Framework is an open-source ORM framework for .NET applications supported by Microsoft. It enables developers to work with data using objects of domain specific classes without focusing on the database tables where this data is stored.

 

 

Database Initialization:- The base constructor of the context class can have the following parameter.

·         No Parameter

·         Database Name

·         Connection String Name

 

    public class SchoolContext:DbContext

    {

        public SchoolContext():base("DefaultConnection"){ }

 

        public DbSet<Student> Student { get; set; }

    }

 

 

Database Initialization Strategy:- We need to define the database initialization strategy in the context class in order to modify domain classes.

·         CreateDatabaseIfNotExistst(default)

·         DropCreateDatabaseIfModelChanges

·         DropCreateDatabaseAlways

·         Custom DB Initializer

 

To use one of the above DB initialization strategies, you have to set the DB Initializer using the Database class in a context class.

 

 public class SchoolDBContext : DbContext

    {

        public SchoolDBContext() : base("SchoolDBConnectionString")

        {

            Database.SetInitializer<SchoolDBContext>(new CreateDatabaseIfNotExists<SchoolDBContext>());

 

            //Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseIfModelChanges<SchoolDBContext>());

            //Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseAlways<SchoolDBContext>());

            //Database.SetInitializer<SchoolDBContext>(new SchoolDBInitializer());

        }

 

        public DbSet<Student> Students { get; set; }

        public DbSet<Standard> Standards { get; set; }

    }

 

 

Disable Database Initializer

 

Database.SetInitializer<CodeFirstContext>(null);

 

However, there are some problems with these database initilization strategies, for example if you already have data (other than seed data) or existing Stored Procedures, triggers etc. in your database. These strategies used to drop the entire database and recreate it, so you would lose the data and other DB objects.

 

Entity Framework introduced a migration tool that automatically updates the database schema when your model changes without losing any existing data or other database objects. It uses a new database initializer called MigrateDatabaseToLatestVersion.

 

There are two kinds of Migration:

 

·         Automatic Migration

·         CodeFirst Migration

 

Enable Autmatic Migration in CodeFirst

1.Automatic Migration

Step1:-

AutomaticMigrationsEnabled = true;

AutomaticMigrationDataLossAllowed = true;

Step2:-

Database.SetInitializer(new MigrateDatabaseToLatestVersion<EmployeeDbContext, Migrations.Configuration>("EmployeeDbContext"));

 

Turn Off Autmatic Migration

AutomaticMigrationsEnabled = false;  

(By Default Automatic migration is false in Configuration.cs file of Migration folder)

 


 

Basic rule to migrate change in the database (Code Based Migration) 

·          enable-migrations(this command runs one for both type migration)

·          add-migration  'Migration_Name'

·          update-database

·          get migration

 


 

Seed and Sql Method:- To seed data into your database you need to override seed method. Seed method is to initialize data into a database that is being created by CodeFirst or evolved by migration. The seed method takes the database context object as an input parameter, and the code in the method use that object to add new entities to the database.

https://www.tutorialspoint.com/entity_framework/entity_framework_seed_databaseHYPERLINK "https://www.tutorialspoint.com/entity_framework/entity_framework_seed_database.htm".htm

entityframeworktutorial.net/code-first/seed-database-in-code-first.aspx

 

NOTE:- We used Seed method only to initialzed our database with some dummy data  or we used this against with Development Database. To seed refrence data(i.e, list of country,list of categories) that we want to deploye Production Database create an empty migration and use sql method to populate our database. 

For sql method see codewithmosh mvc and entity

 

 

CodeFirst Default Convention:- Conventions are sets of default rules which automatically configure a conceptual model based on your domain classes when working with the Code-First approach.

·         Convention for Table, Schema, and Column Names

·         Convention for Keys

·         Convention for String Properties

·         Convention for Byte Array

·         Convention for Booleans

·         Convention for Relationship

·         Convention for Complex Types

 

 

1.Convention For Relationship:-

• If your classes contain a reference and a collection navigation property, Code First

assumes a one-to-many relationship.

 

• Code First will also assume a one-to-many relationship if your classes include a

navigation property on only one side of the relationship (i.e., either the collection

or the reference, but not both).

 

• If your classes include two collection properties, Code First will use a many-tomany

relationship by default.

 

• If your classes include two reference properties, Code First will assume a one-to-one

relationship.In the case of one-to-one relationships, you will need to provide some additional information so that Code First knows which entity is the principal and which is

the dependent.

 

2.Convention for Complex Type:-A type that has no key property and is used as a property in one or more mapped types will be recognized by Code First convention as a complex type. Code First will presume that the properties of the complex type are contained in the table to which the host type maps. and use [Complex] attribute on complex type.

1. Complex types have no key property.

2. Complex types can only contain primitive properties.

3. When used as a property in another class, the property must represent a single

instance. It cannot be a collection type.

 

Overriding Convention :- We can override default conventions by configuring your domain classes to provide EF with the information it needs. There are two ways to configure your domain classes: Data Annotation Attributes and Fluent API.

Data Annotation: Data Annotations or Custom Validation Attributes override default CodeFirst conventions. Data Annotations is used to configure model class and validate data on client side and server side.

Ovverriding Default Convention is called data annotaion.It is limited so we have another concept called Fluent API.

        [Table]

        [Key]

        [ForeignKey]

        [DatabaseGenerated]

        [Column)]

        [Display]

        [DisplayName]

        [DisplayFormat]

        [DisplayColumn]

        [Required]

        [MinLength]

        [MaxLength]         

        [StringLength]  

        [Range]    

        [DataType]       

        [RegularExpression]

        [ConcurrencyCheck]

        [Timestamp]             

        [EmailAddress]

        [Compare]

        [Phone]

        [Index]

        [NotMapped]      

        [ScaffoldColumn]

        [ComplexType]

        [InverseProperty]       

        [MetadataType]     

 

 

FluentAPI: FluentAPI is an advance way of specifying model configuration that covers everything that Data annotations can do in addition to some more advance configuration not possible with Data Annotations. FluentAPI and Data Annotations can be used together.

 

Loading Related Data:-

1.Lazy Loading :-  Lazy loading is delaying the loading of related data, until we specifically request for it. It is the opposite of eager loading.                            

Lazy Loading means loads the related data on demand. With lazy loading, we only retrieve the amount of data that we need in a single query. When we need more data related to the initial data, additional queries are issued to the database. This means there are several round trips between the application server and the database server. In general, these database round trips are very often the major performance bottleneck in most applications. Lesser the round trips, better the performance. Lazing Loadin is good for Desktop Application. 

TurnOff:- Lazy Loading can be disable using        1.this.Configuration.LazyLoadingEnabled = false; in context class                                  2.By Removing virtual keywork from base entity.

  public virtual DbSet<Department> Departments { get; set; }       

 

N+1 Problem With Lazy Loading :-  With lazy loading there is a problem called     n + 1 select problem. Let us understand this problem with an example. In this example there is a One-to-Many relationship between Department and Employee entities. A Department can have 1 or more employees.


Now, let's say we need to iterate through all the Departments, and for each Department, we want to print the list of the employees. By default, LINQ to SQL would do the following:

Select * from Departments

/* For each Department */

SELECT * FROM Employees WHERE DepartmentId = X


So, this means we have one select for the Departments, and then N additional selects to retrieve the employees belonging to each Department, where N is the total number of Departments. So, this is N + 1 problem.

1.Eager Loading:- Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query, so that we don't need to execute a separate query for related entities. Eager loading is achieved using the Include() method. Eager Loading Solve the n+1 problem of LazyLoading.                           With eager loading, all the data is retrieved in a single query, which can then be cached to improve the application performance. With eager loading we are trading memory consumption for database round trips.Eager Loading is good for Web Application. https://www.entityframeworktutorial.net/eager-loading-in-entity-framework.aspx

3.Explicit Loading :-When lazy lazing loading is off. we achieve Lazy Loading with explicit call(Load Method).                                                https://docs.microsoft.com/en-us/efHYPERLINK "https://docs.microsoft.com/en-us/ef/ef6/querying/related-data"/ef6/querying/related-data   https://www.tutorialspoint.com/entity_framework/entity_framework_lazy_loading.htm                                                                                                                              Note:-

·         Lazy Loading achieve by Dynamic Proxy.

·         Eager Loading achieve by Include method.

·         Explicit Loading achive by DbContext Class.

 

 

Table Splitting and Entity Splitting:-

1.Table Splitting:-Mapping multiple entities to a single table is called table splitting.Table Splitting is useful when we want to delay the some properties with large data when using lazy loading.

     Page No-95:-Allowing Multiple Entities to Map to a Single Table:

aka Table Splitting

2.Entity Splitting: Entity Splitting refers to mapping an entity to two or more tables when the two tables share a common key.

 

Inheritance Hierarchy:-

·         Table per type(TPH):-

      Page No-109 :-Working with Code First’s Default Inheritance: Table Per Hierarchy (TPH).

 

·         Table per hierarchy(TPT):-

     Page No-113:-Configuring Table Per Type (TPT) Hierarchy.

 

·         Table per concrete type(TPC):-

      Page No-115:-Configuring for Table Per Concrete Type (TPC) Inheritance.

  

 

 

 

DbContext Vs ObjectContext:- The main difference between DBContext and ObjectContext is that DBContext is a wrapper of the ObjectContext and denotes the most commonly used features of the ObejctContext, while the ObejctContext is a part of the core Entity Framework API that allows performing operations on the database using strongly typed entity classes.

Previously, EDM used to generate context class that was derived from the ObjectContext class. Working with ObjectContext class was a little complex.

ObjectContext is the class that allows us to interact with database using a conceptual model. The Context let us express and execute queries; track change to object and persist those changes back to the database.

 

DbContext is easy in all the development models such as CodeFirst, ModelFirst, and DatabaseFirst. ObjectContext is only useful in ModelFirst and DatabaseFirst.

 

DbContext API is mostly targeted at simplifying your interaction with entity framework. It also reduces the number of methods and properties you need to access commonly used task. In previous versions of entity framework, these tasks were often complicated to discover and code. The context class manages the entity objects during run time, which includes populating objects with data from a database, change tracking, and persisting data to the database.

We can cast DbContext to IObjectContextAdapter interface to access the underlying ObjectContext.

DbContext and ObjectContext also called ContextClass.

 

 

T4 Template:-  T4 stands for Text template transformation toolkit which is a template-based code generation engine built in Visual Studio. It is available in Visual studio from Visual Studio 2008 and higher version of Visual Studio.

 

T4 templates in entity framework are used to generate C# or VB entity classes from EDMX files. Visual Studio 2013 or 2012 provides two templates- EntityObject Generator and DBContext Generator for creating C# or VB entity classes. The additional templates are also available for download.

 

ContextClass:- It represents a session with the underlying database using which you can perform CRUD operations. An instance of Context Class represent Unit of Work and Repository pattern where it can combine multiple changes under a single database transaction. The Context class is used to query or save data to the database. It is also used to configure domain classes, database related mappings, change tracking setting, cashing transaction.

Connected and Disconnected scenario:- Connected scenario is when an entity is retrieved from the database and modified in the same context.

Disconnected scenario is when an entity is retrieved from the database and modified in the different context.

Note: Entities that are not being tracked by a context are known as disconnected entities.

Cascade Delete:- Cascade delete automatically deletes dependent records or sets null to Foreign Key columns when the parent record is deleted in the database.Cascade delete is enabled by default in Entity Framework for all types of relationships such as one-to-one, one-to-many and many-to-many.

 

Entity Framework:- Prior to .NET 3.5, we (developers) often used to write ADO.NET code or Enterprise Data Access Block to save or retrieve application data from the underlying database. We used to open a connection to the database, create a DataSet to fetch or submit the data to the database, convert data from the DataSet to .NET objects or vice-versa to apply business rules. This was a cumbersome and error prone process. Microsoft has provided a framework called "Entity Framework" to automate all these database related activities for your application.

Entity Framework is an open-source ORM framework for .NET applications supported by Microsoft. It enables developers to work with data using objects of domain specific

classes without focusing on the underlying database tables and columns where this data is stored. With the Entity Framework, developers can work at a higher level of abstraction when they deal with data, and can create and maintain data-oriented applications with less code compared with traditional applications.

Official Definition: “Entity Framework is an object-relational mapper (O/RM) that enables .NET developers to work with a database using .NET objects. It eliminates the need for most of the data-access code that developers usually need to write.”

The following figure illustrates where the Entity Framework fits into your application.


 

As per the above figure, Entity Framework fits between the business entities (domain classes) and the database. It saves data stored in the properties of business entities and also retrieves data from the database and converts it to business entities objects automatically.

Entity Framework Features

·         Cross-platform: EF Core is a cross-platform framework which can run on Windows, Linux and Mac.

·         Modelling: EF (Entity Framework) creates an EDM (Entity Data Model) based on POCO (Plain Old CLR Object) entities with get/set properties of different data types. It uses this model when querying or saving entity data to the underlying database.

·         Querying: EF allows us to use LINQ queries (C#/VB.NET) to retrieve data from the underlying database. The database provider will translate this LINQ queries to the database-specific query language (e.g. SQL for a relational database). EF also allows us to execute raw SQL queries directly to the database.

·         Change Tracking: EF keeps track of changes occurred to instances of your entities (Property values) which need to be submitted to the database.

·         Saving: EF executes INSERT, UPDATE, and DELETE commands to the database based on the changes occurred to your entities when you call the SaveChanges() method. EF also provides the asynchronous SaveChangesAsync() method.

·         Concurrency: EF uses Optimistic Concurrency by default to protect overwriting changes made by another user since data was fetched from the database.

·         Transactions: EF performs automatic transaction management while querying or saving data. It also provides options to customize transaction management.

·         Caching: EF includes first level of caching out of the box. So, repeated querying will return data from the cache instead of hitting the database.

·         Built-in Conventions: EF follows conventions over the configuration programming pattern, and includes a set of default rules which automatically configure the EF model.

·         Configurations: EF allows us to configure the EF model by using data annotation attributes or Fluent API to override default conventions.

·         Migrations: EF provides a set of migration commands that can be executed on the NuGet Package Manager Console or the Command Line Interface to create or manage underlying database Schema.

 

Entity Data Model:- The Entity Data Model (EDM) is an extended version of the Entity-Relationship model which specifies the conceptual model of the data using various modeling technique. It also refers to a set of concepts that describe data structure, regardless of its stored form.

EDM supports a set of primitive data types that define properties in a conceptual model. We need to consider 3 core parts which form the basis for Entity Framework and collectively it is known as Entity Data Model. Following are the three core parts of EDM.

·         The Storage Schema Model

·         The Conceptual Model

·         The Mapping Model

 

·         Conceptual Model:  Entity framework builds the conceptual model from our domain class, context class, default convention followed in domain class and configuration. The conceptual model also called as Conceptual Schema Definition Layer (CSDL) is the real entity model against which we write us our queries.(Representation of Entity)

·         Storage Model: Entity framework builds the storage model for the underlying database schema. In the Code First Approach this will be inferred from conceptual model. In Database First Approach, this will be inferred from the targeted database. The Storage model also called as Storage Schema Definition Layer (SSDL) represents the schematic representation of the backend store.(Representation of Database)

·         Mapping: Entity framework includes mapping information on how the conceptual model maps to the database schema (Storage Model).(Represent relation between conceptual model and storage model)

Mapping between Conceptual Model and Storage Model

Storage Model:  Representation of database objects

Table/View

Procedure/Function

Constraints

 

Conceptual Model: Representation of Types

Entity types

Complex types:-

Enum types

      Association types

      Function imports

      Entity Constraints

 

EF performs CRUD operations using this EDM. It uses EDM in building SQL queries from LINQ queries, building INSERT, UPDATE, and DELETE commands, and transform database result into entity objects.

Querying: EF API translates LINQ-to-Entities queries to SQL queries for relational databases using EDM and also converts results back to entity objects.


Saving: EF API infers INSERT, UPDATE, and DELETE commands based on the state of entities when the SaveChanges () method is called. The Change Track keeps track of the states of each entity as and when an action is performed.


 


LINQ to Entities: LINQ-to-Entities (L2E) is a query language used to write queries against the object model. It returns entities, which are defined in the conceptual model. You can use your LINQ skills here.

Entity SQL: Entity SQL is another query language (For EF 6 only) just like LINQ to Entities. However, it is a little more difficult than L2E and the developer will have to learn it separately.

Object Service: Object service is a main entry point for accessing data from the database and returning it back. Object service is responsible for materialization, which is the process of converting data returned from an entity client data provider (next layer) to an entity object structure.

Entity Client Data Provider: The main responsibility of this layer is to convert LINQ-to-Entities or Entity SQL queries into a SQL query which is understood by the underlying database. It communicates with the ADO.Net data provider which in turn sends or retrieves data from the database.

ADO.Net Data Provider: This layer communicates with the database using standard ADO.Net.

 

Entity State:-EF API maintains the state of each entity during its lifetime. Each entity has a state based on the operation performed on it via the context class. The entity state represented by an enum System.Data.Entity.EntityState in EF 6 with the following values:

 


Added: When an entity is in the added state you have few options. In fact you can only detach it from the context.

Modified: When and entity is modified, that means it was in unchanged state and then some property was changed.

Deleted:  An entity enters the deleted state because it was unchanged and then then delete object method was used.

Unchanged:  When an entity is unchanged, it is bound to the context but it has not been modified.

Detached: Detached is the default state of a newly created entity because the context can’t track the creation of any object in your code.

The Context not only holds the reference to all the entity objects as soon as retrieved from the database, but also keeps track of entity states and maintains modifications made to the properties of the entity. This feature is known as Change Tracking.

The change in entity state from the Unchanged to the Modified state is the only state that's automatically handled by the context. All other changes must be made explicitly using proper methods of DbContext or DbSet. (You will learn about these methods in EF 6 and EF Core sections.)

EF API builds and executes the INSERT, UPDATE, and DELETE commands based on the state of an entity when the context.SaveChanges () method is called. It executes the INSERT command for the entities with Added state, the UPDATE command for the entities with Modified state and the DELETE command for the entities in Deleted state. The context does not track entities in the Detached state. The following figure illustrates the significance of entity states:

Edmx in Entity Framework:-

·         An .edmx file is an XML file that defines an Entity Data Model (EDM), describes the target database schema, and defines the mapping between the EDM and the database. An .edmx file also contains information that is used by the ADO.NET Entity Data Model Designer (Entity Designer) to render a model graphically.

·         .edmx is basically an XML file which is generated when we added Entity Framework model. It is Entity Data Model Xml which contains designer (Model) and code file (.cs).

·         Database first allows you to reverse engineer a model from an existing database. The model is stored in an EDMX file (.edmx extension) and can be viewed and edited in the Entity Framework Designer. The classes that you interact with in your application are automatically generated from the EDMX file.

Change Tracker:-Change Tracker responsible for keeping track of the state of object in DbContext.

 

Entity:- An entity in Entity Framework is a class that maps to a database table. This class must be included as a DbSet<TEntity> type property in the DbContext class. EF API maps each entity to a table and each property of an entity to a column in the database.

·         Poco Entity (Plain Old CLR Object): POCO stands for “plain old” CLR object which can be used as existing object with your data model.

·         Dynamic Proxy Entity (Poco proxy)

Note:-  this.Configuration.ProxyCreationEnabled = false;

 

Entity Relationship:- Relationship in DBMS Any association between two entity types is called a relationship. Entities take part in the relationship. It is represented by a diamond shape. For example, A teacher teaches students. Here, "teaches" is a relationship and this is the relationship between a Teacher entity and a Student entity.

One to One:-A one-to-one (1:1) relationship means that each record in Table A relates to one, and only one, record in Table B, and each record in Table B relates to one, and only one, record in Table A.

Ex-Student and Address

 

One to Many:-A one-to-many (1:N) relationship means a record in Table A can relate to zero, one, or many records in Table B. Many records in Table B can relate to one record in Table A.

Ex-Customer and Order

 

Many to Many:-Many-to-many relationships. A many-to-many relationship occurs when multiple records in a table are associated with multiple records in another table.

Ex-Student and Course

 

Note:-Why use ICollection and not IEnumerable or List<T> on many-to-many/one-to-many relationships?

Usually what you choose will depend on which methods you need access to. In general - IEnumerable<> (MSDN: http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx) for a list of objects that only needs to be iterated through, ICollection<> (MSDN: http://msdn.microsoft.com/en-us/library/92t2ye13.aspx) for a list of objects that needs to be iterated through and modified, List<> for a list of objects that needs to be iterated through, modified, sorted, etc (See here for a full list: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx).

 

From a more specific standpoint, lazy loading comes in to play with choosing the type. By default, navigation properties in Entity Framework come with change tracking and are proxies. In order for the dynamic proxy to be created as a navigation property, the virtual type must implement ICollection.

 

A navigation property that represents the "many" end of a relationship must return a type that implements ICollection, where T is the type of the object at the other end of the relationship. -Requirements for Creating POCO Proxies.

 

Entity Properties:-

1.Scalar Property:-The primitive type(int,string etc) properties are called scalar properties.

It stores the actual data.It maps to single column in database table.

 

    public class Student

    {

        // scalar properties

        public int StudentID { get; set; }

        public string StudentName { get; set; }

        public DateTime? DateOfBirth { get; set; }

        public byte[] Photo { get; set; }

      

     }

 

2.Navigation Property:-A Navigation property is a property that helps navigate from one entity to another entity.

The navigation property represents relationship to another entity.By default, navigation properties are null, they are not loaded by default.  For loading navigation property, we use “include” method of IQuearable and this type of loading is called Eager loading.

There are two type of navigation 1.Reference navigation 2.Collection Navigation

 

Reference Navigation:-if an entity includes property of another entity type then it is called reference navigation property.

 

    public class Student

    {

        //reference navigation properties

         public Grade Grade { get; set; }

    }

 

Collection Navigation:-If an entity includes property of collection type then it is called collection navigation.

 

    public class Grade

    {

        public int GradeId { get; set; }

        public string GradeName { get; set; }

        public string Section { get; set; }

 

        public ICollection<Student> Students { get; set; }

    }

 

3.Inverse Property:- Code First convention can identify bidirectional relationships, but not when there are multiple bidirectional relationships between two entities.Then we use Inverse Property.

 

        [InverseProperty("PrimaryContactFor")]

        public Person PrimaryContact { get; set; }

        [InverseProperty("SecondaryContactFor")]

        public Person SecondaryContact { get; set; }

 

Note:-  How to create a Foreign Key in EnityFramework.

 

 

 

 

No comments:

Post a Comment