Hello All,
In this tutorial, we will see how to start with ASP.NET Core web API with Entity Framework core.
I will use Visual Studio 2022 community edition in this tutorial and .NET 6.0 core, Entity Framework Core 6.0, and SQL Server 2019 community edition.
I will use Database First Approach, using an existing SQL database to scaffold the required entities. There are two ways to scaffold the SQL database.
- Using a visual studio extension - EF Core Power Tools (for various tools link is provided below in the description) and
- Reverse engineering – using commands in the package manager console.
A little brief about Entity Framework Core
Entity Framework is an ORM-Object-relational mapping framework that helps to represent the Database into the object-oriented programming model in the .NET Core ecosystem helping to interact and perform CRUD operation on relational DB without hassle. EFCore brings a higher level of abstraction and helps create data-oriented applications with less code and in an efficient way.
So let's get started.
First, let's install the EF Core power tools. Open the browser, search for EF Core power tools Marketplace, and click on the first link (or use this link: https://marketplace.visualstudio.com/items?). Download the extension ( this extension is for Visual Studio). Once downloaded, double-click the extension and follow the wizard to complete the installation. This will add an extension to Visual Studio.
Next below is the simple SQL server database containing two tables (employee and countries). We will use EF core power tools to connect to the SQL Server database, scaffold the Employee table, and generate entities in Visual Studio. The script is uploaded to GitHub.
Next, we will create ASP.NET Core Web API using Visual Studio 2022.
Let's start visual studio. Select File => New Project.
On the "Create a new project template" => Select Blank solution => select Next
Solution Name : ASPNETCore_WebAPI_EFCore_Demo. Click on Create
To create the ASP.NET Core Web API project, click on the solution and click => New Project. Select ASP.NET Core Web API and Click Next
On the Configure New Project - Enter the project name WebAPI_Demo. Select the location you want to create the project and click on Next.
On the Additional information – keep the default selection. Click Create, then wait until visual studio finishes project initialization.
Once the project is created, do a quick test by running the project locally by pressing F5 or clicking the Run button.
The project will build, and once the application runs, the default browser will start, and you will see the default API swagger documentation page. You will be seeing the WeatherForecast API.
Note: The WeatherForcast API is the default API provided out of the box as part of the ASP.NET Core Web API template.
Note: We will delete the default WeatherForecast API. Delete the WeatherForecastController.cs from the controller's folder and WeatherForecast.cs file in Solution Explorer.
Next, we will connect the SQL Server database using the EF Core Power Tools.
Note: We installed the EFP Core Prower Tools Extension earlier in the tutorial.
Right-click on the project => select EF Core Power Tools => Select Reverse Engineer
The "Choose the Database connection" window will pop up. Click on Add => Add Database Connection.
In the connection properties window. Enter the Server Name, then select the database from the list of databases.
Click on Test Connection to test.
Once the Database is connected, keep the default setting and click on OK
On the Choose Database Objects - Select the Employee Table and Click OK.
The Generate EF Core Model in Project window will pop up. You can keep the default information or make changes like Context name, Entity Types path, etc. Click OK (make the changes highlighted in Red).
This will auto-generate the DbContext and the entities user the Models folder (EmployeeContext.cs and the Employees.cs files).
The EF core power tools will also generate a readme file (PowerToolsReadMe.txt). Follow the instruction and make changes to program.cs and appsettings.json files.
Register the data context in the program.cs file, and to the appsettings.json add the connection string.
// Add services to the container.
builder.Services.AddSqlServer<EmployeeContext>(builder.Configuration.GetConnectionString("DefaultConnection"));
Next, we will create a new controller representing the employee's endpoint, allowing the GET, POST, and delete operations on the SQL database through the entity Framework core. Before that, we need to add 2 nugget packages to our controller.
On the Solution Explorer, right-click on the project and select manage nugget packages.
Select the browse tab and type in 'EntityFrameworkCore', select 'Microsoft.EntityFrameworkCore' (6.0.0) package, click on install and follow the installation process. Next, search for EntityFrameworkCore.SqlServer (6.0.0) package, click on install, and follow the installation process.
Now we will add the controller. To add a new controller, Right click on the Controllers folder => click on Add => and select Controller.
By default, MVC is selected. We are creating API, so select API from the installed section (on the left), then select "API Controller – Empty." (on the right), and then Click on Add.
Then type the name of the controller. In this case, EmployeeController as we are creating the Employee endpoint.
The Employee Controller is created.
We must create the Employee endpoint like the GET / POST / DELETE to interact with the Database and perform the CURD Operations.
Copy the below code to create the Employee GET endpoint.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebAPI_Demo.Models;
namespace WebAPI_Demo.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
private EmployeeContext _employeeContext;
public EmployeeController(EmployeeContext employeeContext)
{
_employeeContext = employeeContext;
}
//GET API
[HttpGet]
public async Task<IActionResult> Get()
{
var employees = await _employeeContext.Employees.ToListAsync();
if (employees == null) { return NotFound(); }
return Ok(employees);
}
}
}
Build the project and Press F5 or the Run button to run the application. Once the application runs, the default browser will start, and you will see the default API swagger documentation page. You see the Employee GET endpoint.
You can Try it out - Click "Try it out" then click on Execute, and you will get the Response.
We successfully created ASP.NET Core Web API with EntityFramework Core and connected to SQL server DB to get the Employee data. Similarly, you can write the Endpoints for POST and DELETE.
You can find the complete code on my Github.
https://github.com/HussainPatel/ASPNETCore_WebAPI_EFCore_Demo
You can see the complete video for the above tutorial on Youtube and this Youtube