ASP.Net Web API with Entity Framework

Part 1: Create Web API Project

1. Create a database according to your needs.



2. Create a Asp.Net Web API project.
3. Install Entity Framework from NuGet.
4. Generate model from database by adding 'ADO.Net Entity Data Model' and connecting to your database using the wizard it provides.

Read how to do it: https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/database-first-development/creating-the-web-application



5. Create Web API controller with actions using Entity Framework.


6. Create Data Transfer Objects to transfer data from Web API
NOTE: Don't use Entity Framework models because it will gives you a serializing error
Read more on DTO: https://docs.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-5

Ex: Create ProductModel to use other than Product object which created by Entity Framework

7. Change controller method's return type to newly created DTO type


Original Method: public IQueryable<Product> GetProducts() - Use Entity Framework model
Changed Method: public IQueryable<ProductModel> GetProducts() - Use our DTO model


Part 2: Create Asp.Net MVC Application 

1. Create a Asp.Net MVC application from another solution
2. Create same objects as DTOs created in Web API project
3. Install Newtonsoft Json to project using NuGet
4. Use HttpClient in System.Net.Http assembly to communicate with Web API


5. Create required views using templates.


6. Go to the action in browser to view the results which come from Web API as Json.


NOTE:
You can skip Part 2 of this blog and check the API's action using Postman.
Desktop Application: https://www.getpostman.com/
Google Chrome App: https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en





Happy API callings... :)

Comments

Popular posts from this blog

Deploy Angular 8 app to Azure with Azure DevOps

Apache ActiveMQ 5 with .Net Core 3.1 and C#

Firebase with.Net Core and C#