Set up .NET Core Web API With Entity Framework Core
Tags: netcore, webdev, restapi, efcore
Published: 2024-04-17 12:53:00

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; }
}
```

**_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<Product> 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();
});
```