Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Part 1 - What is Entity Framework



What is Entity Framework
Entity Framework is an ORM framework. ORM stands for Object Relational Mapping.

What is Object Relational Mapping framework
Object Relational Mapping framework automatically creates classes based on database tables, and the vice versa is also true, that is, it can also automatically generate necessary SQL to create database tables based on classes.



Let's understand what entity framework can provide with an example. Assume we have the following 2 tables
Entity framework example

Entity framework example in asp.net

We want to display the above data from both the tables in a webform as shown below.
asp.net entity framework example

To achieve this
1. We need to create Department and Employee classes
2. Write ADO.NET code to retrieve data from the database
3. Once the data is retrieved we need to create Department and Employee objects and populate them with data.

Entity Framework can do all of the above automatically, if we provide it with the database schema.

Installing NuGet Package Manager
1. From Visual Studio 2010 Tools menu, select Extension Manager
2. Click on Online Gallery in the Extension Manager window
3. Search for NuGet 
4. Finally Download NuGet Package Manager and install
Installing NuGet Package Manager

Please note: You must restart visual studio for the changes to take effect.

Step 1: Create a new "Empty ASP.NET Web Application" with name=Demo.

Step 2: Installing Entity Framework
a) Click on Tools - NuGet Package Manager - Manage NuGet Packages for solution
b) Click on "Online" tab in "Manage NuGet Packages" window
c) Type "EntityFramework" in the search textbox on the top right hand corner
d) Finally click on the "Install" button.
Installing Entity Framework

At this point Entity Framework version 6.1 is installed and a reference to EntityFramework assembly is also automatically added.
Installing Entity Framework 6.0

Step 3: Create "Departments" and "Employees" tables.
Create table Departments
(
     ID int primary key identity,
     Name nvarchar(50),
     Location nvarchar(50)
)

Create table Employees
(
     ID int primary key identity,
     FirstName nvarchar(50),
     LastName nvarchar(50),
     Gender nvarchar(50),
     Salary int,
     DepartmentId int foreign key references Departments(Id)
)

Step 4: Populate the tables created in Step 3, with data
Insert into Departments values ('IT', 'New York')
Insert into Departments values ('HR', 'London')
Insert into Departments values ('Payroll', 'Sydney')

Insert into Employees values ('Mark', 'Hastings', 'Male', 60000, 1)
Insert into Employees values ('Steve', 'Pound', 'Male', 45000, 3)
Insert into Employees values ('Ben', 'Hoskins', 'Male', 70000, 1)
Insert into Employees values ('Philip', 'Hastings', 'Male', 45000, 2)
Insert into Employees values ('Mary', 'Lambeth', 'Female', 30000, 2)
Insert into Employees values ('Valarie', 'Vikings', 'Female', 35000, 3)
Insert into Employees values ('John', 'Stanmore', 'Male', 80000, 1)

Step 5: Right click on the project in solution explorer and add ADO.NET Entity Data Model. Change the name from Model1.edmx to EmployeeModel.edmx
Creating ADO.NET Entity Data Model using Schema First approach

Step 6: Select "Generate from database" and click "Next"

Step 7: Choose Your Data Connection
a) Click on "New Connection" button
b) Select "Microsoft SQL Server" as Data source, and ".Net Framework Data Provider for SQL Server" option from "Data provider" dropdownlist. Click Continue.
c) On "Connection Properties" screen, specify SQL Server Name. If you are using local installation of SQL Server then use (local) or . in the "server name" dropdownlist.
d) Specify the Authentication you want to use.
e) Select the database from "Select or enter database name" dropdownlist.
f) Finally "Test connection" and click "OK"
g) At this point we should be back on "Choose Your Data Connection" window. Make sure "Save entity connection settings in Web.Config as" checkbox is selected and change the name of the connection string to "EmployeeDBContext" and then Click "Next"

Step 8: On "Choose Your Database Objects" screen, select "Departments" and "Employees" tables. Change the Model Namespace to "EmployeeModel" and click "Finish". At this point you should have EmployeeModel.edmx created.
Entity framework data model example

EmployeeModel.Designer.cs file is also generated. This file contains Employee and Department classes. Tables are mapped to classes and columns are mapped to class properties.

Step 9: Add a webform. Drag and drop a GridView and an EntityDataSource control on the webform.

Step 10: Build the solution. Flip the WebForm1.aspx to design mode. 
a) Right click on EntityDataSource control and select "Show smart tag" option from the context menu.
b) Click on "Configure Data Source" link
c) Select "Named Connection" radiobutton and select "EmployeeDBContext" from the dropdownlist.
d) Select "EmployeeDBContext" option from "DefaultContainerName" dropdownlist and click "Next"
e) On "Configure Data Selection" screen, select "Departments" from "EntitySetName" dropdownlist and click "Finish"
f) Right click on "GridView1" control and select "Show smart tag" option.
g) Click on "Auto Format" link and select "Colorful" option from "AutoFormat" window and click "OK".
h) Select "EntityDataSource1" from "Choose Data Source" dropdownlist.
I) Click on "Eidt Columns" link and add a "Template Field". Set HeaderText=Employees and click OK.
j) Now click "Edit Templates" link.
k) Drag and drop a GridView control
l) Select "Edit DataBindings" link 
m) Select "Custom binding" radiobutton and type Eval("Employees") in "Code expression" textbox and click OK.
n) Select "End Template Editing" option from "GridView1" smart tasks pane.

Step 11: Right click on "EntityDataSource1" control and select "Properties". In properties window set Include=Employees

Run the web application and notice that Departments and Employees are displayed as expected. We have achieved all this without writing a single line of code.

In this demo, we have used schema first approach of entity framework. We can also use Model First or Code First approaches. We will discuss these in our subsequent videos.
using entity framework in asp.net example

Entity Framework Tutorial

37 comments:

  1. Hi Venkat,

    I am getting the below error when executing your example. Can you please help

    The result type of the query is neither an EntityType nor a CollectionType with an entity element type. An Include path can only be specified for a query with one of these result types.

    ReplyDelete
  2. At step 8 the EmployeeModel.Designer.cs file is also generated BUT does not contains Employee and Department classes.

    I just have some text // T4 code generation is enabled for model ….. but no class code? Would appreciate if you would help me resolve the issue. Thanks

    ReplyDelete
  3. Hi Venkat,

    I am getting the below error when executing your example. Can you please help

    The result type of the query is neither an EntityType nor a CollectionType with an entity element type. An Include path can only be specified for a query with one of these result types.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. // Default code generation is disabled for model 'E:\New folder\learning\MVC4\MVCprojectsSelfLearning\EntityFrameworkDemo\EntityFrameworkDemo\EmployeeModel.edmx'.
    // To enable default code generation, change the value of the 'Code Generation Strategy' designer
    // property to an alternate value. This property is available in the Properties Window when the model is
    // open in the designer.

    please help me to fix this

    ReplyDelete
    Replies
    1. how did you fix this? I am having same issue

      Delete
  6. Hi Venkat,

    I am getting the below error Can you please help
    1)The provider did not return a ProviderManifest instance. Could not determine storage version; a valid storage connection or a version hint is required

    2)The metadata specified in the connection string could not be loadedmetadata. Consider rebuilding the web project to build assemblies that may contain metadata.

    ReplyDelete
  7. Hi Venkat,

    I am getting the below errors upon following the steps mentioned in video. Please advise.
    Error 1 Partial declarations of 'WebApplication1.SampleDbContext' must not specify different base classes
    Error 2 Type 'WebApplication1.SampleDbContext' already defines a member called 'SampleDbContext' with the same parameter types
    Error 3 Type 'WebApplication1.SampleDbContext' already defines a member called 'SampleDbContext' with the same parameter types
    Error 4 Type 'WebApplication1.SampleDbContext' already defines a member called 'SampleDbContext' with the same parameter types
    Error 5 Type 'WebApplication1.SampleDbContext' already defines a member called 'OnModelCreating' with the same parameter types
    Error 6 The type 'WebApplication1.SampleDbContext' already contains a definition for 'Departments'
    Error 7 The type 'WebApplication1.SampleDbContext' already contains a definition for 'Employees'
    Error 8 The type 'WebApplication1.SampleDbContext' already contains a definition for 'Departments'WebApplication1
    Error 9 The type 'WebApplication1.SampleDbContext' already contains a definition for 'Employees'WebApplication1
    Error 10 The type 'WebApplication1.Department' already contains a definition for 'ID'
    Error 11 The type 'WebApplication1.Department' already contains a definition for 'Name'
    Error 12 The type 'WebApplication1.Department' already contains a definition for 'Location'
    Error 13 The type 'WebApplication1.Department' already contains a definition for 'Employees'
    Error 14 The type 'WebApplication1.Employee' already contains a definition for 'ID'
    Error 15 The type 'WebApplication1.Employee' already contains a definition for 'FirstName'
    Error 16 The type 'WebApplication1.Employee' already contains a definition for 'LastName'
    Error 17 The type 'WebApplication1.Employee' already contains a definition for 'Gender'
    Error 18 The type 'WebApplication1.Employee' already contains a definition for 'Salary'
    Error 19 The type 'WebApplication1.Employee' already contains a definition for 'DepartmentId'
    Error 20 The type 'WebApplication1.Employee' already contains a definition for 'Department'

    ReplyDelete
    Replies
    1. try to change code generation Property to Default by clicking on the designer surface and get Properties
      then delete tow files with tt extension , rebuild Solution and it will work well
      check the second answer in this
      http://stackoverflow.com/questions/14865038/errors-appear-after-changing-code-generation-from-none-to-default-in-entity-fram

      Delete
  8. How to filter employee records? Ex: I want to display only Male employees. Then where to make change? Please tell me using any approach [Schema, Model or Code] Thanks

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. I am facing the same error (unable load the specified meta data resource). When i am configuring the Entity Data Source. I build my solution but facing same error. more over delete tt file and already ProviderManifestToken="2008".
    So please help me.

    ReplyDelete
    Replies
    1. Compile the project first

      Delete
    2. Getting this error when i am compile this project. then what are u saying "Compile the project first"

      Delete
    3. I have Surpasses this situation but m not able to Select Default Connection

      Delete
    4. Please Try Re-Build the project and compile again.

      Delete
  11. hello sir,
    while inserting the values the table of employees in MS-SQL ,i got the following error ('String or binary data would be truncated.The statement has been terminated.').I don't understand what does it really mean. Please help me out , where i am lacking.

    Regards
    Abhishek

    ReplyDelete
  12. After getting rid of the above error that i mentioned, i got the different error i.e.( " The INSERT statement conflicted with the FOREIGN KEY constraint "FK__employees__depar__2BFE89A6". The conflict occurred in database "synapse", table "dbo.departments", column 'id'.
    The statement has been terminated.")

    ReplyDelete
  13. When I am running my project, its not displaying DataGridView on browser..! kindly help me out in it.

    ReplyDelete
  14. In EmployeeModel.Designer.cs file there are no classes and properties-

    I was getting the text as below-

    // T4 code generation is enabled for model 'D:\VisualStudio2015\EntityFramework\Demo\EmployeeModel.edmx'.
    // To enable legacy code generation, change the value of the 'Code Generation Strategy' designer
    // property to 'Legacy ObjectContext'. This property is available in the Properties Window when the model
    // is open in the designer.

    // If no context and entity classes have been generated, it may be because you created an empty model but
    // have not yet chosen which version of Entity Framework to use. To generate a context class and entity
    // classes for your model, open the model in the designer, right-click on the designer surface, and
    // select 'Update Model from Database...', 'Generate Database from Model...', or 'Add Code Generation
    // Item...'.

    when i tried to configure the data source as in step - 10 b I was getting an error as

    Entity Data Source wizard is only compatable with Entity Frame work 5.
    I am using EF6 and VS2015.

    I tried a lot but not able to solve this.., please help me...,

    ReplyDelete
    Replies
    1. Dowmngrade Entity Framework Version 5

      Delete
    2. getting same error.do you know how to solve ?

      Delete
  15. EmployeeModel.Designer.cs file contains text as below- please help me

    // T4 code generation is enabled for model 'D:\VisualStudio2015\EntityFramework\Demo\EmployeeModel.edmx'.
    // To enable legacy code generation, change the value of the 'Code Generation Strategy' designer
    // property to 'Legacy ObjectContext'. This property is available in the Properties Window when the model
    // is open in the designer.

    // If no context and entity classes have been generated, it may be because you created an empty model but
    // have not yet chosen which version of Entity Framework to use. To generate a context class and entity
    // classes for your model, open the model in the designer, right-click on the designer surface, and
    // select 'Update Model from Database...', 'Generate Database from Model...', or 'Add Code Generation
    // Item...'.

    ReplyDelete
  16. Entity Data Source wizard is only compatable with Entity Frame work 5.
    I am using EF6 and VS2015.

    Resolve this problem downgrade your Entity Framework version 5

    ReplyDelete
    Replies
    1. Hi Manish, how to downgrade to Entity framework 5 from 6

      Delete
    2. go to Nuget Pacakge Manager, now move to installed tab and you can see your EF 6 installed. then click on it and select versio 5.0.0 from the dropdown and then update.
      My opinion would be instead of downgrading an alreaady installed EF from your project, create a new project with EF version 5.0.0 selected while referencing.

      Delete
  17. Using Visual Studio 2017, how do I create the kind of project I need here? I have tried both new site and new project, both creates insane amount of classes and pages, while I just want the stuff needed for this demo.

    ReplyDelete
  18. Hi, I have just started with Schema first approach. Entity model was created bu in designer.cs there are not entity and contexts.
    I tried to click 'update model from database'. there i am unable to select(click) any tables in Add tab.

    could someone help me how to get them?

    thanks in advance,
    Sailaja

    ReplyDelete
  19. Dropdown value of Default Container name not appearing

    ReplyDelete
  20. Hi, can someone answer me how to alter the table using Entity Framework Code first approach without losing data in the table?

    ReplyDelete
  21. when click on Configure Data Source,
    This version of the entity data source wizard is only compatible with entity Framework 5. If you are not using entity framework 5 you can configure the control by editing the markup on the page.............

    Note: using VS 2017
    EF- 6.2.0

    ReplyDelete
  22. Hi, can anyone please provide the link to download Entity framework 5.

    ReplyDelete
    Replies
    1. Download EF5 using Nuget Package Manager from your Visual Studio

      Delete
  23. Hi Sir, I got a problem to install entity framework from my visual studio 2012. I did follow your guides but got the message "The underlying connection was closed :An unexpected error occurred on a send." I have tried to google for the solution but failed. If you could give me some advise that would be good as I'm keen to start learning.
    Thanks in advance.

    ReplyDelete
  24. Hi Sir,
    I wanting to start your Entity Framework tutorial after watching your "How to become full stack developer video" but I just got stuck in your first tutorial because of the EntityDataSource configuration issue. I have installed Entity Framework V6.4.4.
    I also installed the Microsoft.AspNet.EntityDataSource and Microsoft.AspNet.DynamicData.EFProvider from the nudget package. But then , I drag and drop the EntityDataSource control from toolbox to my web form. I want to configure the data source but Error Message pop up
    "THIS VERSION OF THE ENTITY DATA SOURCE WIZARD IS ONLY COMPATIBLE WITH ENTITY FRAMEWORK 5.IF YOU'RE NOT USING ENTITY FRAMEWORK 5 YOU CAN CONFIGURE THE CONTROL BY EDITING THE MARKUP ON THE PAGE.THE PAGE EDITOR HAS INTELLISENSE SUPPORT FOR ASP.NET CONTROLS.IF YOU'RE USING ENTITY FRAMEWORK 6 YOU SHOULD ALSO BE USING THE EF-6 COMPATIBLE VERSION OF THE ENTITY DATA SOURCE CONTRL, AVAILABLE AS THE MICROSOFT.ASPNET.ENTITYDATASOURCE PACKAGE IN NuGet."

    So I follow the error message and installed the entity datasource control and dynamicdata provider from Nudget but still cannot configure. I read some posting for same issue to change the prefix for the control to "ef" then my Entitydatasouce smart tag disable.

    I hope you read my messages and could give me some advice otherwise I have no choice but can't proceed to learn. I try to google for the solution but my effort is in vain.

    ReplyDelete
    Replies
    1. The EntityDataSource that you are using from ToolBox section uses EntityFramework 5, but you have added EntiryFramwork 6 from the NuGet Package Manager. Hence you wont be able to configure Data Source.

      To resolve this issue, remove the reference of EF6 from your project and install EF5 from the NuGet Package Manager.This can be cumbersome as dependency for EF6 is stored at various places in your project and will throw errors later so I would suggest you to easily create a new project then while adding EntityFramework, select version 5.0.0 from the dropdown.

      Then follow the normal steps as mentioned in the tutorial and you wont find any errors.

      Delete

It would be great if you can help share these free resources