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
We want to display the above data from both the tables in a webform as shown below.
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
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.
At this point Entity Framework version 6.1 is installed and a reference to EntityFramework assembly is also automatically added.
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
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.
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.
Hi Venkat,
ReplyDeleteI 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.
At step 8 the EmployeeModel.Designer.cs file is also generated BUT does not contains Employee and Department classes.
ReplyDeleteI 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
Hi Venkat,
ReplyDeleteI 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.
This comment has been removed by the author.
ReplyDelete// Default code generation is disabled for model 'E:\New folder\learning\MVC4\MVCprojectsSelfLearning\EntityFrameworkDemo\EntityFrameworkDemo\EmployeeModel.edmx'.
ReplyDelete// 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
how did you fix this? I am having same issue
DeleteHi Venkat,
ReplyDeleteI 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.
Hi Venkat,
ReplyDeleteI 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'
try to change code generation Property to Default by clicking on the designer surface and get Properties
Deletethen 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
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
ReplyDeleteYou can use LINQ queries to filter records
DeleteThis comment has been removed by the author.
ReplyDeleteI 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".
ReplyDeleteSo please help me.
Compile the project first
DeleteGetting this error when i am compile this project. then what are u saying "Compile the project first"
DeleteI have Surpasses this situation but m not able to Select Default Connection
DeletePlease Try Re-Build the project and compile again.
Deletehello sir,
ReplyDeletewhile 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
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'.
ReplyDeleteThe statement has been terminated.")
When I am running my project, its not displaying DataGridView on browser..! kindly help me out in it.
ReplyDeleteIn EmployeeModel.Designer.cs file there are no classes and properties-
ReplyDeleteI 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...,
Dowmngrade Entity Framework Version 5
Deletegetting same error.do you know how to solve ?
DeleteEmployeeModel.Designer.cs file contains text as below- please help me
ReplyDelete// 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...'.
Entity Data Source wizard is only compatable with Entity Frame work 5.
ReplyDeleteI am using EF6 and VS2015.
Resolve this problem downgrade your Entity Framework version 5
Hi Manish, how to downgrade to Entity framework 5 from 6
Deletego 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.
DeleteMy 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.
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.
ReplyDeleteHi, I have just started with Schema first approach. Entity model was created bu in designer.cs there are not entity and contexts.
ReplyDeleteI 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
Dropdown value of Default Container name not appearing
ReplyDeleteHi, can someone answer me how to alter the table using Entity Framework Code first approach without losing data in the table?
ReplyDeletewhen click on Configure Data Source,
ReplyDeleteThis 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
Hi, can anyone please provide the link to download Entity framework 5.
ReplyDeleteDownload EF5 using Nuget Package Manager from your Visual Studio
DeleteHi 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.
ReplyDeleteThanks in advance.
Hi Sir,
ReplyDeleteI 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.
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.
DeleteTo 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.