Set up .NET Core Web API With Entity Framework Core

RMAG news

In this article, we will take one example to walk through the steps to set up a .NET Core WEB API with CORS(Cross-Origin Resource Sharing) enabled , and database with Entity Framework hosted in Microsoft SQL Server.

CORS allows a web server to handle cross-origin requests from web applications hosted on different domains. This is particularly useful when you’re building a client-server application where the client, typically a JavaScript-based web application, needs to interact with the API hosted on a different domain.

After finish, we can use swagger UI to test API endpoints .

Let’s get ready with Prerequisites

Prerequisites

Tool : Visual Studio 2022
DS : Microsoft SQL Server
Now let’s start to build up .NET Core Web API project

Step 1: Create a New .NET Core Web API Project

First, let’s create a new .NET Core Web API project. Select ASP.NET Core Web API template . and set up project name
Keep default setting and select framework to the latest version .

Step 2: Add two required packages of Entity Framework for this project with nuget manager

Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools

Step 3: Set up folders and add connection string for this API application

Models folder : in Models folder , create two folders — Domains folder and Dtos folders. In each folder , add domain models and DTO models for this project. Domain Object covers all the concepts with real-world data tables , while DTO( data transfer object) is responsible for the mapping between backend and frontend .
Data folder : The folder will host DbContext class . DbContext is responsible for the connection to database , tracking changes, perform CRUD (create, read, write, delete) operations and mapping between domain object and database.
appsettings.json : add “ConnectionStrings” section and within it specify the connectionstring key and proper value that is able to connect to SQL server .
//sample of dbContext

public class PMSDbContext:DbContext
{
public PMSDbContext(DbContextOptions options):base(options)
{

}
public DbSet<Product> Products { get; set; }
}

Step 4: Register the dbContext to program’s service

builder.Services.AddDbContext<PMSDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString(“your connection string”)));

Step 5: Execute Entity Framework Core command to migrate model’s definition to create table script and execute the create table script to database

Add-Migration “your migration name”
Update-Database

Step 6: Repository Design pattern

Create Repository folder , under Repository , set up Interface and Implementation folders
In Interface folder , set up an Interface file for CRUD action .
public Task CreateAsync(Product product);
In Implementation folder , set up an class derived from the interface and do the implementation part .

public async Task<Product>CreateAsync(Product product)
{
await dbContext.Products.AddAsync(product);
await dbContext.SaveChangesAsync();
return product;
}

Remember to inject the dependency to program.cs , after register the scope , we can easily inject the interface and use.

builder.Services.AddScoped<IProductRepository, ProductRepository>();

Step 7: Now set up the api’s controller and implement the endpoints for httppost , httpget ,httpput , httpdelete verbs.

[HttpPost]
public async Task<IActionResult> Create([FromBody] Addproductdto request)
{
// map request to product

// call productrepository to do create data
await productRepository.CreateAsync(product);

// map product to productdto

return Ok(response);
}

Step 8: Running the application , we can use swagger to test the endpoint .

Step 9: Remember to add CORS policy in programs before your frontend project starts to communicate with your api projects.

app.UseCors(options =>
{
options.AllowAnyHeader().AllowAnyOrigin().AllowAnyOrigin().AllowAnyMethod();
});

Leave a Reply

Your email address will not be published. Required fields are marked *