MVC - REST Web API SQL Server Connection Using Entity Framework Database First Approach
MVC - REST Web API SQL Server Connection Using Entity Framework Database First Approach
The example code is being developed in Microsoft Visual Studio 2019 Professional. I
have taken the data sample from AdventureWorks for SQL server 2014.
Let's begin now.
Step 1
Create new Web API project and name it "RESTWebApiGetMethod".
Step 2
Although you can create your entity framework model inside any hierarchy of the
project, I prefer "Models" folder, to keep code cleaner. So, right click on your
"Models" folder and then click "Add->ADO.NET Entity Data Model" as shown below
i.e.
Step 3
Now, from "Entity Data Model Wizard" choose "EF Designer from database", since I
am creating entity framework database first approach model. Then click "Next" as
shown below i.e.
Step 4
On the "Choose Your Data Connection" window, click "New Connection" button and
create your SQL server connection as shown below i.e.:
Step 5
Now, on "Choose Your Data Connection" window, click "Yes, include sensitive data
in connection string" option and click "Next" as shown below i.e.:
Step 6
Now, on "Choose Your Database Objects and Settings" window, choose your target
database objects. In my case, I have select only the store procedures. Then click
"Finish" as shown below i.e.:
Step 7
Create "Controllers\WebApiController.cs" file.
Step 8
Create a global parameter in "Controllers\WebApiController.cs" file to access
DbContext of your SQL server connection and name it "databaseManager".
Step 9
Now, create "Get" method without parameter inside
"Controllers\WebApiController.cs" file and replace the following code in it i.e.:
1. ...
2. public HttpResponseMessage Get()
3. {
4. // Initialization
5. HttpResponseMessage response = null;
6. DataTable responseObj = new DataTable();
7. string json = string.Empty;
8. ...
9. // Loading Data from SQL server.
10. var data = this.databaseManager.GetProductByPric
eGreaterThan1000().ToList()
11. ...
12. // Process data
13. ...
14. // Create HTTP Response.
15. ...
16. // Info.
17. return response;
18. }
19. ...
In this article, you learned to create REST Web API connection with SQL server Entity
Framework Database First approach using ASP.NET REST Web API platform. You learned
about creating GET type method with input request parameter. You learned to load data
from SQL server using entity framework database first approach and finally, you learned to
test REST Web API using any REST client to see your REST Web API in action before
consumption.
https://www.c-sharpcorner.com/article/asp-net-mvc-rest-web-api-sql-server-connection-using-entity-
framework-database/?
fbclid=IwAR1e6EnZMDOuppoEHH6MYEOt6IMvo0PeC_rAsgeJMg2Hz0afBV_cGTLevwc