This is part 6 of Web API tutorial series. In this article, I have demonstrated using Entity Framework with Web API to communicate with SQL Server. In this article, database first approach has been explained.
To start with Entity Framework, you need to add EntityFramework project in your solution. In this article we demonstrated each step to setup Entity Framework. We will use existing project, add EF project, import database table and replace all code with LINQ query. Finally we will validate the implemetation using MVC application.
Step 1) To Setup EF project, let's add a class library and name it "EntityFrameworkLayer".
Step 2) Now try to add Entity Template. Unfortunately you will not find it as there is no such template exist as it has to install via Nuget package.
Step 3) Right click solution and click on "Manage Nuget Package".
Step 4) Search EntityFramework in nuget. It will show Entity Framework package. Now select all the projects where you want to install EF. In our case it is EntityFrameworkLayer and WebAPI project. EntityFramework 6 will get install when you click Install button.
Step 5) Now addd new item in EntityFrameworkLayer and Select Data tab. Select ADO.Net Entity Data Model and name it "EFEntityModel".
Step 6) A wizard opens, follow as mentioned below. In this demo, we are using Database-First apporach. Wizard will setup database connection, save it to App.config file, import all tables which want to import and show a diagram for the same. We imported only employee table as this is the only table we have. An entity context class will be created, here we named it PRACCONEntities and a model named PRACCONModel is created which have all POCO classes.
Here you can see the EDMX file created having tables in diagram form.
Here you can see the connection string added in App.config file. copy this connection string in Web API project as well.
Here is the entity structure.
Step 7) Now add a class EmployeeManager and add below code to fetch employee data from database using LINQ query.
Above code wll not run, add below code to it. You need to convert your data into Enumerable else it will not convert into long using Convert.ToInt64().
Step 8) In EmployeeController in Web API project, add below code to call EntityFramework methods using EmployeeManagement class.
Step 9) Test the Web API using MVC application.
Hope this helps you.