Friday, 5 August 2016

Restful API with Entity Framework | 3-Tier WebApi

Let create new WebApi using 3-Tier Architecture. Open  VS 2015 >New Projects > Visual C#  >  Web> ASP.Net Web Application and add empty webapi projects for service and then data layers as shown below.
Add EntityFramwork reference using nuget manager in Datalayer. We would build a model from Database (Database First approach)
In datalayer, lets add a new model; right click > add new item > Data > Choose ADO.NET Entity Data Model and provide model name and click add.
Choose EF Designer from DB and provide the connection string and then choose the product table and click finish.
Product model is shown below,
In Service layer, lets add a service interface and  implementation for it, let build webapi for GET Operations
Include reference of datalayer. Here is the service implementation for Get and GetById methods, these methods read the data from the model using EF.
In WebApi project, add a product controller and then include references of service and datalayer. Lets Implement GET operations as shown below,
Run the Webapi project and browse urls as shown below, model is rendered from the product table as shown.
Lets add a breakpoint and hit api/product url.

Similarly, add a breakpoint and hit api/product/2 url.
Let refactor the code for the Get Operation with Id,
Browse for product 3, empty product is rendered

No comments:

Post a Comment

Note: only a member of this blog may post a comment.