Monday 22 September 2014

An Introduction to Entity Framework

What is Entity Framework :

 

Entity Framework (EF) is an object-relational mapper (ORM) that enables .NET developers to work with relational data using domain-specific objects. It basically generates business objects and entities according to the database tables and allow us to perferm basic CRUD (Create, Read, Update, Delete) operations,maintaining relationship (1 to 1, 1 to many, many to many) and also provides ability to have inheritance relationships between entities. 


What is ORM :

ORM is a tool for storing data from domain objects to relational database like MS SQL Server.ORM includes three main parts: 

                1.Domain class objects
                2.Relational database objects
                3.Mapping information on how domain objects map to relational database objects
                  (tables, views & stored procedures).

ORM allows us to keep our database design separate from our domain class design.It also automates standard CRUD operation (Create, Read, Update & Delete) so that the developer doesn't need to write it manually.



Why to use EF  OR What is the Advantage of using it :

  • It increases the productivity by reducing the development time. It eliminates the need of writing the data-access code as the framework itself provides the core data access capabilities.So developers can only concentrate on application logic.
  • Decreases the maintainability as we have the fewer lines of code to fetch data from database,so fewer lines of code we have to maintain. This is very effective for big projects.
  • Applications are free from hard-coded dependencies on a particular data engine or storage schema. Its is a conceptual model which is independent of physical model. We can easily run our application using different RDBMSs (MySql, MS SQL,SQLite ,Oracle etc.), only by changing configurations.

Is it an alternative to ADO.NET :

 

The answer would be "yes and no". Yes because the developer will not be writing ADO.NET methods and classes for performing data operations and No because this model is actually written on top of ADO.NET, which means this framework still uses ADO.NET. So EF can neither replaces nor succeeds ADO.NET.


Important versions history of EntityFramework:


EntityFramework Version                             Introduced Features
EF 3.5 Basic O/RM support with Database First approach.
EF 4.0 POCO Support, Lazy loading, testability improvements, customizable code generation and the Model First approach.
EF 4.1 First to available of NuGet package, Simplified DBContext API over ObjectContext, Code First workflow.
EF 4.1.1 In addition to bug fixes for EF 4.1 this patch release introduced some components to make it easier for design time tooling to work with a Code First model.
EF 4.2 This release includes bug fixes to the EF 4.1.1 release.
EF 4.3 Code First Migrations feature that allows a database created by Code First to be incrementally changed as your Code First model evolves.
EF 4.3.1 patch released with bug fixing of EF 4.3.
EF 5.0 Announced EF as Open Source. Introduced Enum support, table-valued functions, spatial data types, multiple-diagrams per model, coloring of shapes on the design surface and batch import of stored procedures, EF Power Tools and various performance improvements.
EF 6.0 It includes many new features related to Code First & EF designer like asynchronous query & save, connection Resiliency, dependency resolution,Improved transaction support etc.
EF 6.0.1 The 6.0.1 patch release is limited to fixing issues that were introduced in the EF6 release (regressions in performance/behavior since EF5).
EF 6.0.2 patch released with bug fixing some performance and functional issues of EF 6.
EF 6.1 This minor release adds few new features to EF6.It includes Tooling consolidation,handling of transaction commit failure and Index attribute

Hope this will help you.. :)

Monday 15 September 2014

How to Create a Entity Framework model and Use it in a separate .Net Project

This article elaborate the steps required to create an Entity Data Model and re-use it in a separate .Net Project like a Console Application, a Windows Forms project, ASP.NET Project or a WPF Project.

Consider a situation where you have created a entity data model using an existing database and you want that to use in another projects. Then a question arises is this possible ,If yes then how i can achieve this? Below are the steps which will guide you to create a Entity data model and use it in another .Net project. 

Here is my previous link which will describes you how to create a entity data model from an existing database.Once it is created then the below steps will describe you how to use this model in a Console Application.

Using the Entity Model in a Console Application 
 
We will now use the model we created above, in a Console Application.
Step 1: RightClick on solution > Add > New Project > In the templates, select Windows > Console Application. Make sure the target framework is '.NET Framework 4.5'. Give it a name. We are using 'ConsoleAppUsingEFModel'. Click Ok.  
 
Step 2: Let us now add a reference to the model we created earlier, in this console application. Right click on the project > Add Reference > Go to solution folder > Projects > select the EntityFrameworkModel.dll as shown below. Click OK.


Step 3: Add a reference to the System.Data.Entity. Right click on the project > Add Reference > Go to Assemblied folder > Framework > select the System.data.entity.dll as shown below. Click OK.

   
Step 4: Then we need to provide the connection string information to the new console application. You can achieve this in two ways:
 
(a)By adding the connectionstring entry of 'EntityFrameworkModel' into the app.config file of 'consoleAppUsingEFModel' project.  
(b)By copying the App.config file of EntityFrameworkModel project in 'ConsoleAppUsingEFModel' project.(Right click the project > Add Existing Item > Go to the EntityFrameworkModel project and add the App.config file.)
 
Step 5: In this final step you need to add the Entityframework dll from the NuGet Packages. Right Click on Solution explore > Manage Nuget Packages for Solution > Go to Online > NuGet offical package source > In the search box search for EntityFramework > Click on install. Select Project Popup will open. Select the two projects > Click on Ok > License Acceptance popup will open > Click on I Accept > Click on close to close the NugetPackage.


 
Step 6: Build the solution and make sure that it is erorr free.Once the steps shown above are completed, you now need to add data in database (LogInDetail Table) using the below codes. Open Program.cs and add two name spaces :
using System.Data.Entity;
using EntityFrameworkModel;

Write the following query in your Main method.
static void Main(string[] args)
{
        using (var context = new EFDatabaseFirstEntities())
        {
              try
             {
                     var loginDetails = new LogInDeatil
                     {
                            UserName = "pallavipraharaj",
                            Password = "password",
                            DateCreated = DateTime.Now
                     };
                     context.LogInDeatils.Add(loginDetails);
                     context.SaveChanges();
                     Console.WriteLine("EFModel is successfully used in another .net project.");
                     Console.ReadKey();
             }
             catch (Exception ex)
             {
                   throw ex;
              }
        }
}

That’s all! You have now created a model and used that one in another .NET project. 
Here is the demo.Have a look.