Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

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

13 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
  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
    Replies
    1. You can use LINQ queries to filter records

      Delete
  9. 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
  10. 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
  11. 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

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.