<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Sunny@skillsoft</title>
    <description>The latest articles on DEV Community by Sunny@skillsoft (@muchasskillsoft).</description>
    <link>https://dev.to/muchasskillsoft</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1268578%2F23b4bffb-5049-4ac6-8dce-73b933ab6af7.png</url>
      <title>DEV Community: Sunny@skillsoft</title>
      <link>https://dev.to/muchasskillsoft</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/muchasskillsoft"/>
    <language>en</language>
    <item>
      <title>Set up .NET Core Web API With Entity Framework Core</title>
      <dc:creator>Sunny@skillsoft</dc:creator>
      <pubDate>Wed, 17 Apr 2024 12:53:00 +0000</pubDate>
      <link>https://dev.to/muchasskillsoft/set-up-net-core-web-api-with-entity-framework-core-m8d</link>
      <guid>https://dev.to/muchasskillsoft/set-up-net-core-web-api-with-entity-framework-core-m8d</guid>
      <description>&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;After finish, we can use swagger UI to test API endpoints .&lt;/p&gt;

&lt;p&gt;Let’s get ready with Prerequisites&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Tool : Visual Studio 2022&lt;/li&gt;
&lt;li&gt;DS : Microsoft SQL Server
Now let’s start to build up .NET Core Web API project&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Step 1: Create a New .NET Core Web API Project&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

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

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Step 2: Add two required packages of Entity Framework for this project with nuget manager&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Microsoft.EntityFrameworkCore.SqlServer&lt;/li&gt;
&lt;li&gt;Microsoft.EntityFrameworkCore.Tools&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Step 3: Set up folders and add connection string for this API application&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;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 .&lt;br&gt;
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.&lt;br&gt;
appsettings.json : add “ConnectionStrings” section and within it specify the connectionstring key and proper value that is able to connect to SQL server .&lt;br&gt;
//sample of dbContext&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class PMSDbContext:DbContext
{
    public PMSDbContext(DbContextOptions options):base(options)
    {

    }
    public DbSet&amp;lt;Product&amp;gt; Products { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;Step 4: Register the dbContext to program’s service&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;builder.Services.AddDbContext&amp;lt;PMSDbContext&amp;gt;(options =&amp;gt;
   options.UseSqlServer(builder.Configuration.GetConnectionString("your connection string")));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;Step 5: Execute Entity Framework Core command to migrate model’s definition to create table script and execute the create table script to database&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Add-Migration “your migration name”&lt;/li&gt;
&lt;li&gt;Update-Database&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Step 6: Repository Design pattern&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public async Task&amp;lt;Product&amp;gt;CreateAsync(Product product)
{
    await dbContext.Products.AddAsync(product);
    await dbContext.SaveChangesAsync();
    return product;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember to inject the dependency to program.cs , after register the scope , we can easily inject the interface and use.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;builder.Services.AddScoped&amp;lt;IProductRepository, ProductRepository&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;Step 7: Now set up the api’s controller and implement the endpoints for httppost , httpget ,httpput , httpdelete verbs.&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[HttpPost]
public async Task&amp;lt;IActionResult&amp;gt; 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);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;Step 8: Running the application , we can use swagger to test the endpoint .&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Step 9: Remember to add CORS policy in programs before your frontend project starts to communicate with your api projects.&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.UseCors(options =&amp;gt;
{
    options.AllowAnyHeader().AllowAnyOrigin().AllowAnyOrigin().AllowAnyMethod();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>netcore</category>
      <category>webdev</category>
      <category>restapi</category>
      <category>efcore</category>
    </item>
  </channel>
</rss>
