DEV Community

Sunny@skillsoft
Sunny@skillsoft

Posted on

1

Set up .NET Core Web API With Entity Framework Core

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

  1. Tool : Visual Studio 2022
  2. 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; }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Register the dbContext to program’s service

builder.Services.AddDbContext<PMSDbContext>(options =>
   options.UseSqlServer(builder.Configuration.GetConnectionString("your connection string")));
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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>();
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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();
});
Enter fullscreen mode Exit fullscreen mode

Image of AssemblyAI tool

Challenge Submission: SpeechCraft - AI-Powered Speech Analysis for Better Communication

SpeechCraft is an advanced real-time speech analytics platform that transforms spoken words into actionable insights. Using cutting-edge AI technology from AssemblyAI, it provides instant transcription while analyzing multiple dimensions of speech performance.

Read full post

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay