Monday, 1 August 2016

Type of approaches available in Entity Framework

http://www.c-sharpcorner.com/UploadFile/ff2f08/identifying-entity-framework-development-approaches/


The Entity Framework provides three approaches to create an entity model and each one has their own pros and cons.
  1. Database First
  2. Model First
  3. Code First
Database First
The Database First approach enables us to create an entity model from the existing database. This approach helps us to reduce the amount of code that we need to write. The following procedure will create an entity model using the Database First approach.

Step 1
Create the ADO.Net entity data model using the "Generate from Database" option.



Step 2
Select an existing connection or create new connection from "Choose Your Data Connection" windows and after this select database object (such as table, view and Stored Procedure) that are required into the project.



This will generate with selected entities and association (relationship among entities).



To update the model (in case of a database change), right-click on the model and select the “Update Model from Database” option and follow from Step 2.



Advantages
  • This approach is very popular when we have an existing database
  • The EDM wizard creates the entities and their relationships automatically
  • Extensibility is possible using a partial class or T4 templates
  • We need to write less code and put less effort into creating the entity model
  • Easy update if any changes are made to the database
Disadvantages
  • Very difficult to maintain a complex model
  • Model customization is very difficult. In other words, if we don't have a foreign key in the database and we need an association in the conceptual layer then we must create it manually and it is very difficult to maintain when we update the model from the database.
Model First
In this approach, model classes and their relation is created first using the ORM designer and the physical database will be generated using this model. The Model First approach means we create a diagram of the entity and relation that will be converted automatically into a code model.

The following procedure will create an entity model using the Model First approach.

Step 1
Create the ADO.net entity data model using the "Empty EF Designer Model" option.



Step 2
Now create the entity. Step 1 created the empty entity model. To add a new entity just right-click on the diagram and select “Add new” and the entity option. Fill in the entity name and database table name and primary key information.



Step 3
Now to add properties to the entity.



Step 4
Add associations (relation among entities) if any.



Step 5
Once the entity model design is completed, we can generate the database from this model using the "Generate Database from model" context menu option. Here we can select any existing database connection or create a new database connection to create the database from a model.



Step 5 will generate the DDL script and this generated file will be added to the solution as a script file.





Advantages
  • Visual designer to create a database schema
  • Model diagram can be easily updated when the database changes
  • Entity Framework generates the Code and database script
  • Extensibility is possible using a partial class
Disadvantages
  • When we change the model and generate SQL to sync the database then this will always result in data loss because the tables are dropped first.
  • We don't have much control on entities and database.
  • Requires a good knowledge of Entity Framework to update the model and database
Code First
The Code First approach enables us to create a model and their relation using classes and then create the database from these classes. It enables us to work with the Entity Framework in an object-oriented manner. Here we need not worry about the database structure.

As said earlier, we need to create a class that represents the database table. As an example I have created the two classes Employee and EmployeeDetails.
  1. public partial class Employee  
  2. {  
  3.     public int EmployeeId { get; set; }  
  4.   
  5.     [StringLength(10)]  
  6.     public string Code { get; set; }  
  7.   
  8.     [StringLength(50)]  
  9.     public string Name { get; set; }  
  10.   
  11.     public virtual EmployeeDetail EmployeeDetail { get; set; }  
  12. }  
  13.   
  14. public partial class EmployeeDetail  
  15. {  
  16.     [Key]  
  17.     [DatabaseGenerated(DatabaseGeneratedOption.None)]  
  18.     public int EmployeeId { get; set; }  
  19.   
  20.     [StringLength(25)]  
  21.     public string PhoneNumber { get; set; }  
  22.   
  23.     [StringLength(255)]  
  24.     public string EmailAddress { get; set; }  
  25.   
  26.     public virtual Employee Employee { get; set; }  
  27. }  
The next step is to create a DbContext class and define a DbSet properties type of entity classes that are represented as a table in the database.
  1. public partial class CodeFirst : DbContext  
  2. {  
  3.     public CodeFirst() : base("name=CodeFirst")  
  4.     {  
  5.     }  
  6.   
  7.     public virtual DbSet<Employee> Employees { get; set; }  
  8.     public virtual DbSet<EmployeeDetail> EmployeeDetails { get; set; }  
  9.   
  10.     protected override void OnModelCreating(DbModelBuilder modelBuilder)  
  11.     {  
  12.     }  
  13. }  
Now if we want to create the database from the model then open the Package Manager Console and follow the migration procedure as shown below.



Step A: Enable Migration

enable-migrations -ContextTypeName “Conext class type with namespace” -MigrationsDirectory:”Migration directory”

Example
PM> enable-migrations -ContextTypeName
EntityFrameworkApproaches.CodeFirst.CodeFirst -MigrationsDirectory:CodeFirst



Step B: Add Migration
Add-Migration -configuration –DbContext –Migrations –Configuration “Class-with-Namespaces” -Migrations- “Name”

Example
PM> Add-Migration -configuration EntityFrameworkApproaches.CodeFirst.Configuration InitialEntities



Step C: Update database
Update-Database -configuration –DbContext – Migrations “Configuration Class withNamespaces” –Verbose

Example
PM> Update-Database -configuration:EntityFrameworkApproaches.CodeFirst.Configuration -Verbose



Advantages
  • There is full control of the model from the code. There is no EDMX/designer and no auto-generated code
  • It supports database migrations, so it is very easy to sync various databases
  • We have more customization options and more control
  • We can also use Code First to map our model to an existing database; to learn more click here
Disadvantages
  • It is very difficult to maintain a database compared to a visual design tool
  • Requires a good knowledge of C# and data annotation
Comparing Approaches



Feature
Entity Framework Approaches
Code First
Model First
Database First
Support ORM designer tool (visual creation of data model)
No.
No EDMX support hence there are no any support of visual creation ofdata model.
Yes.
Yes.
Generates code and database scripts
Yes.
Yes.
NA
In this approach, we already have database and from the database wecreate model.
Extensible through partial classes
NA
In this approach, all are POCO classes,
Yes.
Yes.
Full control over model from code
Yes.
No.
No.
Manual changes to the database are possible?
Yes.
Yes.
Yes.
Easy to modify the model?
Yes.
Yes.
Yes.
An existing database can be used?
Yes.
To know more click here.
NA
Yes.

Selecting Right Approach
Definitely the development approach depends upon the project situation. The following diagram may help us to select the correct approach for your project. As in this diagram, if we already have domain classes, the Code First approach is best suited for our application. The same as if we have a database, Database First is a good option. If we don't have model classes and a database and require a visual entity designer tool then Model First is best suited.



My opinion

It definitely depends on the situation what approach is more suitable for a project / application but after comparing three approaches, I still prefer Code First approaches. I have a couple of reasons for that.
  • Code First supports database migrations.
  • Much simpler to synchronize databases among developers and different versions of the application.
  • More control over the Model. In other words, we have more control over how the entities and associations are created and how they work.

Saturday, 25 June 2016

Links

http://www.entityframeworktutorial.net/code-first/simple-code-first-example.aspx


Entity Framework Questions

1. What is Entity Framework?
2. What are the benefits of using EF?
3. What are the different ways of creating these domain / entity objects?
4. What is pluralize and singularize in EF dialog box?
5. What is importance of EDMX file in EF?
6. Can you explain CSDL, SSDL and MSL section in an EDMX file?
7. What are T4 templates?
8. What is the importance of T4 in EF?
9. Hoe can we read records using EF classes?
10. How can we add, update and delete using EF?

Friday, 24 June 2016

ADO.NET Entity Framework Version History


1) Explain what ADO.NET entity framework is?

ADO.NET entity framework is an ORM (Object Relational Mapping) framework developed by Microsoft. It is an extension of ADO.NET that provides an automated mechanism to access and store data in the database. With the help of ADO.NET, database can be accessed without much required programming or code.


2) Mention what is the key advantage of using Entity Framework or EF?


The main advantage of using Entity Framework or EF is that it generates code automatically for the Model (Middle Layer), Mapping code and Data Access Layer. It reduces a lot of time during the development process.


3) Explain what does .edmx file contains?


.edmx file is an XML file, which declares a conceptual model, a storage model and the mapping between these models.  This file also consists the information that is used by ADO.NET entity data model designer to render a model graphically. It consists of all the mapping details of how object maps with SQL tables.  It is divided into three categories SSDL, CSDL, and MSL.


4) Mention what is CSDL, SSDL and MSL sections in an EDMX file?



• CSDL: It stands for Conceptual Schema Definition Language, it is the conceptual abstraction which is exposed to the application
• SSDL: It stands for Storage Schema Definition Language, it defines the mapping with our RDBMS data structure
• MSL: It stands for Mapping Schema Language, it connects the SSDL and CSDL

5) Mention what is the difference between LINQ to SQL and Entity Framework?
  

        It works only with SQL Server Database

          It works with various database like DB2, MYSQL, SQL Server etc.

        To maintain the relation it generates a .dbml

        It creates an .edmx files initially and relation is maintained using 3 different files .msl, .csdl and .ssdl
 It cannot generate database from model

         It can generate database from model

        It permits one to one mapping between the entity classes and relational views/tables

         Between the entity classes and relational tables, it permits one-to-one, one-to-many and many-to-many

         It enables you to query data using DataContext

         It enables you to query data using EntitySQL, DBContext, and ObjectContext

It provides tightly coupled approach

It provides loosely coupled approach



6) How can you enhance the performance of Entity Framework?


To enhance the performance of Entity Framework, you have to follow the following steps
• Try to avoid to put all the DB objects into one single entity model
• Disable change tracking for entity if not needed
• Reduce response time for the first request by using pre-generating Views
• If not required try to avoid fetching all the fields
• For data manipulation select appropriate collection
• Wherever needed use compiled query
• Avoid using Views and Contains
• While binding data to grid or paging, retrieve only required no of records
• Debug and Optimize LINQ query


7) Explain why T4 entity is important in Entity Framework?


T4 entity is important in Entity framework as it is the heart of entity framework code generation.  It reads the EDMX XML file and generate C# behind code.


8) Explain how you can load related entities in EF (Entity Framework)?


You can load related entities or data in EF in three ways
• Eager Loading
• Lazy Loading
• Explicit Loading


9) Explain Lazy loading, Eager Loading, and Explicit Loading?


• Lazy Loading: It is a process to delay the loading of related objects until it is required.
• Eager Loading: It occurs when you query for an object and all of the related objects are also returned. In eager loading, related objects are loaded automatically with its parent object
• Explicit Loading: Explicitly loading takes place when you have disabled Lazy loading, and you still want to lazy loading. For this, we have to call the load method on the related entities.



10. How many Type of approaches available in Entity Framework?

There are 3 approaches in Entity Framework

  • Database First
  • Model First
  • Code First

Database First

Database first is the approach in which our database has already generated. And using this database we create our Model and code in entity framework.

Model First

In Model first we create designer (model) first. If database not exist then we can create database using this designer

Code First

In code first we create code file first and then if database not exist then database will be created automatically at runtime using this code.

11. What is ObjectContext class in Entity Framework?


ObjectContext is the class which helps us to perform Insert, Update, Delete and create in Entity Framework.

This class is available in System.Data.Entity namespace.

12. Is it necessary to have EDMX file in code first approach


No, it is not necessary.

13. How can we specify key column in Code first approach.


By assigning a [key] attribute on property.

For Example
[Key]
public int emp_id { get; set; }


14. Which namespace we use in Code first approach to use [key] attribute


System.ComponentModel.DataAnnotation

15. Which namespace we use in Code first approach to use [Foreign key] attribute


System.ComponentModel.DataAnnotation.Schema







ADO.NET Entity Framework Version History
ADO.NET Entity Framework Version
6.0
.NET Framework 4.5.1 and Visual Studio 2013
1.     Async Query and Save
2.     Code-Based Configuration
3.     Dependency Resolution
4.     Interception/SQL logging
5.     Improved Connection Management
6.     Improved Transaction Support
 
5.0
.NET Framework 4.5 and Visual Studio 2012
1.     Enum Support in Code First and EF Designer
2.     Spatial Data Types in Code First and EF Designer
3.     Table-Valued Functions
4.     Multiple Diagrams per Model
 
4.3
.NET Framework 4.0 and Visual Studio 2010
1.     Code First Migrations
2.     Automatic Migrations
 
4.2
.NET Framework 4.0 and Visual Studio 2010
1.     The EF 4.2 release included the bug fixes to EF 4.1
 
4.1
.NET Framework 4.0 and Visual Studio 2010
1Code First development
2.     Introduced DbContext API
3.     Data Annotations and Fluent API Validation
 
4.0                               












3.5
.NET Framework 4.0 and Visual Studio 2010
1.     Model-first development
2.     POCO support
3.     Lazy Loading
4.     T4 Code Generation




.NET Framework 3.5 SP1 and Visual Studio 2008 SP1
1. This releaseprovided basic O/RM support using the Database first development