<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ .net core - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ .net core - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 26 Jul 2026 22:34:08 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/net-core/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Build CRUD Operations with .NET Core – A Todo API Handbook ]]>
                </title>
                <description>
                    <![CDATA[ Welcome to this comprehensive guide on building CRUD operations with .NET Core. We'll use a Todo API as our practical example so you can get hands-on experience as you learn.  Throughout this tutorial, you'll learn how to create, read, update, and de... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-crud-operations-with-dotnet-core-handbook/</link>
                <guid isPermaLink="false">66bb56fb3c5ab240beb8cd95</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ crud ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ .net core ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Isaiah Clifford Opoku ]]>
                </dc:creator>
                <pubDate>Fri, 24 May 2024 14:33:16 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/05/Attractive.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Welcome to this comprehensive guide on building CRUD operations with .NET Core. We'll use a Todo API as our practical example so you can get hands-on experience as you learn. </p>
<p>Throughout this tutorial, you'll learn how to create, read, update, and delete Todo items, and how to leverage Entity Framework Core to interact with a database.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></li>
<li><a class="post-section-overview" href="#heading-how-to-enhance-your-development-experience-with-visual-studio-code-extensions">How to Enhance Your Development Experience with Visual Studio Code Extensions</a></li>
<li><a class="post-section-overview" href="#heading-learning-outcomes">Learning Outcomes</a></li>
<li><a class="post-section-overview" href="#heading-what-is-net-core">What is .NET Core?</a></li>
<li><a class="post-section-overview" href="#heading-net-core-vs-net-framework">.NET Core vs .NET Framework</a></li>
<li><a class="post-section-overview" href="#heading-step-1-set-up-your-project-directory">Step 1: Set Up Your Project Directory</a></li>
<li><a class="post-section-overview" href="#heading-step-2-establish-your-project-structure">Step 2: Establish Your Project Structure</a></li>
<li><a class="post-section-overview" href="#heading-step-3-create-the-todo-model">Step 3: Create the Todo Model</a></li>
<li><a class="post-section-overview" href="#heading-step-4-set-up-the-database-context">Step 4: Set Up the Database Context</a></li>
<li><a class="post-section-overview" href="#heading-step-5-define-data-transfer-objects-dtos">Step 5: Define Data Transfer Objects (DTOs)</a></li>
<li><a class="post-section-overview" href="#heading-step-6-implement-object-mapping-for-the-todo-api">Step 6: Implement Object Mapping for the Todo API</a></li>
<li><a class="post-section-overview" href="#heading-step-7-implement-global-exception-handling-middleware">Step 7: Implement Global Exception Handling Middleware</a>  </li>
<li><a class="post-section-overview" href="#heading-step-8-implement-the-service-layer-and-service-interface">Step 8: Implement the Service Layer and Service Interface</a></li>
<li><a class="post-section-overview" href="#heading-step-9-implement-the-createtodoasync-method-in-the-todoservices-class">step 9: Implement the CreateTodoAsync Method in the Service Class</a> </li>
<li><a class="post-section-overview" href="#heading-step-10-implement-the-getallasync-method-in-the-service-class">Step 10: Implement the GetAllAsync Method in the Service Class</a> </li>
<li><a class="post-section-overview" href="#heading-step-11-create-the-todocontroller-class">step 11: Create the TodoController Class  </a> </li>
<li><a class="post-section-overview" href="#step-12">Step 12: Implement the CreateTodoAsync  Method in the TodoController Class</a></li>
<li><a class="post-section-overview" href="#heading-step-13-implement-migrations-and-update-the-database">Step 13: Implement Migrations and Update the Database</a></li>
<li><a class="post-section-overview" href="#heading-step-14-verify-your-api-with-postman">Step 14: Verify Your API with Postman</a></li>
<li><a class="post-section-overview" href="#heading-step-15-retrieve-all-todo-items">Step 15: Retrieve All Todo Items</a> </li>
<li><a class="post-section-overview" href="#heading-step-16-implement-the-getbyidasync-method">Step 16: Implement the GetByIdAsync Method</a></li>
<li><a class="post-section-overview" href="#heading-step-17-implement-the-updatetodoasync-method">Step 17: Implement the UpdateTodoAsync Method</a></li>
<li><a class="post-section-overview" href="#heading-step-18-implement-the-deletetodoasync-method">Step 18: Implement the DeleteTodoAsync Method</a></li>
<li><a class="post-section-overview" href="#heading-step-19-test-your-api-endpoints-with-postman">Step 19: Test Your API Endpoints with Postman</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<p>Before we dive in, let's ensure you're equipped with the necessary prerequisites.</p>
<h2 id="prerequisites">Prerequisites</h2>

<p>Before you get started, make sure you have the necessary tools installed on your machine. Here are the download links:</p>
<ul>
<li><a target="_blank" href="https://dotnet.microsoft.com/download">.NET SDK</a></li>
<li><a target="_blank" href="https://code.visualstudio.com/download">Visual Studio Code</a></li>
<li><a target="_blank" href="https://visualstudio.microsoft.com/downloads/">Visual Studio 2019</a></li>
<li><a target="_blank" href="https://www.postman.com/downloads/">Postman</a></li>
<li><a target="_blank" href="https://www.microsoft.com/en-us/sql-server/sql-server-downloads">SQLServer</a></li>
</ul>
<p>After installing the .NET SDK, it's important to verify its installation and check the version. For this tutorial, we'll be using .NET 8.0.</p>
<p>To check the version of the .NET SDK installed on your machine, open the terminal and run the following command:</p>
<pre><code class="lang-bash">dotnet --version
</code></pre>
<p>If the .NET SDK is installed correctly, the version number will be displayed in the terminal:</p>
<pre><code class="lang-bash">8.0
</code></pre>
<p>If you see a different version number, ensure you have .NET 8.0 installed on your machine.</p>
<h2 id="enhancing-development"> How to Enhance Your Development Experience with Visual Studio Code Extensions</h2>

<p>Visual Studio Code, a lightweight and open-source code editor, is an excellent tool for building .NET Core applications. And you can further enhance its functionality with extensions that streamline the development process. </p>
<p>Here are two recommended extensions for .NET Core development:</p>
<ul>
<li><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit">C# for Visual Studio Code</a></li>
<li><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=adrianwilczynski.namespace">C# Namespace Autocompletion</a></li>
</ul>
<p>To install these extensions, follow these steps:</p>
<ol>
<li>Open Visual Studio Code.</li>
<li>Click on the Extensions icon in the Activity Bar on the side of the window to open the Extensions view.</li>
<li>In the search bar, type the name of the extension.</li>
<li>In the search results, locate the correct extension and click on the Install button.</li>
</ol>
<p>Here's how the Extensions view looks in Visual Studio Code:</p>
<ul>
<li><p>C# Devkit Extension for Visual Studio Code
<img src="https://www.freecodecamp.org/news/content/images/2024/05/DevKIt.png" alt="Extensions view for Devkit" width="600" height="400" loading="lazy"></p>
</li>
<li><p>Namespace Autocompletion Extension for Visual Studio Code
<img src="https://www.freecodecamp.org/news/content/images/2024/05/NameSpace.png" alt="Extensions view for Namespace Autocompletion" width="600" height="400" loading="lazy"></p>
</li>
</ul>
<p>In the images above, the extensions are already installed. If they're not installed on your system, you can do so by clicking on the Install button.</p>
<p>With these essential tools in place, we're now fully equipped to start building our Todo API.</p>
<h2 id="learning-outcomes"> Learning Outcomes </h2>


<p>By the end of this tutorial, you'll have learned how to:</p>
<ul>
<li>Set up a new .NET Core project using the .NET Core CLI</li>
<li>Define a model for a Todo item</li>
<li>Create a database context to interact with the database</li>
<li>Implement routing and controllers for the Todo API</li>
<li>Create a service class to handle business logic</li>
<li>Implement CRUD operations for the Todo API</li>
<li>Handle exceptions globally using middleware</li>
<li>Test the API endpoints using Postman</li>
</ul>
<p>If you're new to C# and .NET, don't worry. I'll explain all the concepts in depth to ensure you understand them. For additional information, you can refer to the <a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/csharp/">C# documentation</a>.</p>
<p>Before we delve into the code, let's clarify what .NET Core is.</p>
<h2 id="what-is-net-core"> What is .NET Core? </h2>

<p>.NET Core, also known as ASP.NET, is a cross-platform framework that facilitates the building of web applications, APIs, and services. It's a free, open-source, and high-performance framework, designed for creating modern, cloud-based, internet-connected applications. It's the successor to the .NET Framework.</p>
<p>But what's the difference between .NET Core and .NET Framework?</p>
<h2 id="net-core-vs-net-framework"> .NET Core vs .NET Framework </h2>

<p>.NET Core and .NET Framework are two distinct frameworks used for application development. .NET Core is a cross-platform framework that operates on Windows, macOS, and Linux. It's a modular, open-source, and free-to-use framework, designed for building modern, cloud-based, internet-connected applications.</p>
<p>On the other hand, <code>.NET Framework</code> is a <code>Windows-only framework</code> used for building <code>Windows desktop</code> <code>applications</code>, <code>web applications</code>, and services. Unlike .NET Core, it's not open-source or free to use. However, it's a mature framework that has been around for a long time.</p>
<p>With a foundational understanding of .NET Core and .NET Framework under your belt, we're ready to dive into building our Todo API.</p>
<p>In this tutorial, we'll leverage .NET Core to construct a Todo API that performs CRUD operations. Our journey will take us through creating a new project, defining the Todo model, setting up the database, and implementing the CRUD operations.</p>
<p>Let's begin with Visual Studio Code. In this tutorial, we'll be using the .NET Core CLI to create our project and build our API. If you prefer Visual Studio 2019, you can follow along using that IDE as well but we will be using Visual Studio Code for this article. </p>
<h2 id="step-1">  Step 1: Set Up Your Project Directory </h2>

<p>First, navigate to the directory where you want to house your project. This could be any folder on your system where you'd like to store your code.</p>
<p>Once you're in the desired directory, open the terminal. You can do this in Visual Studio Code by going to <code>View -&gt; Terminal</code> or by pressing Ctrl + a  backtick.</p>
<p>With the terminal open, type the following command:</p>
<pre><code class="lang-bash">dotnet new webapi -n TodoAPI
</code></pre>
<p>This command instructs the .NET Core CLI to create a new web API project named <code>TodoAPI</code>. The <code>-n</code> option specifies the name of the project.</p>
<p> <img src="https://www.freecodecamp.org/news/content/images/2024/05/TerminalCreatingNewAPI.png" alt="Creating a new API with the .NET Core CLI" width="600" height="400" loading="lazy"></p>
<p>The image above illustrates how to execute the command in the terminal.</p>
<p>After pressing the 'Enter' key, the .NET Core CLI will start generating the necessary files for your project.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/ProjectFile.png" alt=".NET project folder structure" width="600" height="400" loading="lazy"></p>
<p>The image above showcases the generated project structure. It includes all the necessary files and directories required for a .NET Core web API project.</p>
<p>With the project files and folders generated by the .NET Core CLI, let's take a moment to understand the purpose of each file.</p>
<ul>
<li><p><code>appsettings.json</code>: This file houses the application's configuration settings. It's the go-to place for storing connection strings, logging configurations, and other settings.</p>
</li>
<li><p><code>Program.cs</code>: Serving as the application's entry point, this file is responsible for setting up the host and configuring the services.</p>
</li>
<li><p><code>TodoAPI.csproj</code>: This project file contains metadata about your project, including references to the necessary packages and libraries.</p>
</li>
<li><p><code>appsettings.Development.json</code>: This file is designed for configuration settings specific to the development environment. It's ideal for storing environment-specific settings. But for the purpose of this tutorial, we'll be using the <code>appsettings.json</code> file instead.</p>
</li>
<li><p><code>TodoAPI.http</code>: This file is typically used to test API endpoints using the REST Client extension in Visual Studio Code, as it contains sample requests for the API endpoints. However, in this tutorial, we'll be using Postman for testing, so we won't need this file and will proceed to delete it.</p>
</li>
</ul>
<h2 id="step-2">  Step 2: Establish Your Project Structure  </h2>

<p>Having set up our project directory, it's time to lay out the structure of our project. We'll be creating several folders, each with a specific purpose:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/ProjectFolder.png" alt="project folder structure" width="600" height="400" loading="lazy"></p>
<ul>
<li><code>AppDataContext</code>: This folder will contain the database context, which is responsible for interacting with the database.</li>
<li><code>Contracts</code>: This folder will house our Data Transfer Objects (DTOs), which are used to shape the data sent between the client and the server.</li>
<li><code>Models</code>: This folder will contain the Todo model, which represents the structure of a Todo item.</li>
<li><code>Controllers</code>: This folder will house the TodoController, which handles incoming HTTP requests and sends responses.</li>
<li><code>Interfaces</code>: This folder will contain the IService interface, which defines the contract for our service class.</li>
<li><code>Services</code>: This folder will house the Service class, which implements the IService interface and contains the business logic of our application.</li>
<li><code>Mapping</code>: This folder will contain the mapping profile, which is used to map properties between different objects.</li>
<li><code>Middleware</code>: This folder will house the exception middleware, which handles exceptions globally across our application.</li>
</ul>
<p><em>Congratulations!</em> You've successfully set up your project directory and established the project structure. In the next section, we'll delve into defining the Todo model.</p>
<h3 id="heading-how-to-adjust-the-programcs-file-for-controllerbase">   How to Adjust the Program.cs File for ControllerBase </h3>

<p>When creating a new application using the <code>dotnet new webapi</code> command in .NET Core 6 and onwards, the generated project is a minimal web API project. But for this tutorial, we'll be using the traditional way of creating APIs, which requires some adjustments to the <code>Program.cs</code> file.</p>
<p>Before we dive into the changes, let's briefly discuss what a minimal API is.</p>
<h3 id="heading-understanding-minimal-apis">  Understanding Minimal APIs </h3>

<p>In .NET 6, Microsoft introduced a new feature known as Minimal APIs. These APIs are simpler and more lightweight than traditional APIs. They allow you to define your API routes and endpoints using a single file, without the need for controllers or startup classes. This approach facilitates the creation of small, focused APIs that are quick to build and easy to maintain.</p>
<p>However, for the purpose of this tutorial, we'll stick to the traditional API structure. Let's proceed with the necessary changes to the <code>Program.cs</code> file.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/Program.cs.png" alt="Initial view of Program.cs" width="600" height="400" loading="lazy"></p>
<p>The image above displays the initial state of the <code>Program.cs</code> file when you create a new web API project. To adapt it for use with ControllerBase, we need to remove some code and add new code.</p>
<p>Start by deleting everything in the <code>Program.cs</code> file and replacing it with the following code:</p>
<pre><code class="lang-csharp">
 <span class="hljs-comment">// program.cs</span>
<span class="hljs-keyword">var</span> builder = WebApplication.CreateBuilder(args);

<span class="hljs-comment">// Add services to the container.</span>
builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

<span class="hljs-keyword">var</span> app = builder.Build();

<span class="hljs-comment">// Configure the HTTP request pipeline.</span>
<span class="hljs-keyword">if</span> (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
</code></pre>
<p>Now we can proceed to the next step, where we'll define the Todo model.</p>
<h2 id="step-3">  Step 3: Create the Todo Model  </h2>

<p>Before diving into creating our Todo model, it's important to know what a model does in <code>.NET CORE</code>. Think of a <code>model</code> as a <code>blueprint</code> for the kind of data our application will work with. It helps us organize and manage this data efficiently.</p>
<p>For our Todo list app, we need a clear picture of what each Todo item looks like. This means deciding on things like names, descriptions, whether it's done or not, deadlines, priorities, and when it was made or changed. By being clear about these details, we can handle and show our Todo items well.</p>
<h3 id="heading-meet-the-todo-model">  Meet the Todo Model </h3>

<p>Now, let's make our idea real by creating the <code>Todo</code> model. This model is like a template for our Todo items, making sure they have all the right pieces.</p>
<p>Let's create a new file called <code>Todo.cs</code> in the <code>Models</code> folder and fill it with this code:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Models/Todo.cs</span>
<span class="hljs-keyword">using</span> System.ComponentModel.DataAnnotations;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">TodoAPI.Models</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Todo</span>
    {
        [<span class="hljs-meta">Key</span>]
        <span class="hljs-keyword">public</span> Guid Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Title { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Description { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> IsComplete { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
        <span class="hljs-keyword">public</span> DateTime DueDate { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Priority { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
        <span class="hljs-keyword">public</span> DateTime CreatedAt { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
        <span class="hljs-keyword">public</span> DateTime UpdatedAt { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Todo</span>(<span class="hljs-params"></span>)</span>
        {
            IsComplete = <span class="hljs-literal">false</span>;
        }
    }
}
</code></pre>
<p>Here's what each part of the <code>Todo</code> model means:</p>
<ul>
<li><strong>Id</strong>: A special number that makes each Todo item unique.</li>
<li><strong>Title</strong>: The name of the Todo item.</li>
<li><strong>Description</strong>: Extra details about the Todo item.</li>
<li><strong>IsComplete</strong>: Whether the Todo item is finished or not.</li>
<li><strong>DueDate</strong>: The date by which the Todo item needs to be done.</li>
<li><strong>Priority</strong>: How important the Todo item is.</li>
<li><strong>CreatedAt</strong> and <strong>UpdatedAt</strong>: When the Todo item was first made and last changed.</li>
</ul>
<p>The <code>[Key]</code> tag tells us that <code>Id</code> is the main way to identify each Todo item in our database.</p>
<p>By having a clear <code>Todo</code> model, we can easily keep track of and display our Todo items in the best way possible.</p>
<p>In ASP.NET Core, models can be used to represent a variety of things. One such use case is error handling. When an error occurs in our application, we can create a model for that error and return it to the client. </p>
<p>Let's create a model specifically for error handling in our application.</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Models/ErrorResponse.cs</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">TodoAPI.Models</span>
{
       <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ErrorResponse</span>
 {
     <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Title { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
     <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> StatusCode { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
     <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Message { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
 }
}
</code></pre>
<p>This ErrorResponse model will be used to return error messages to the client when an error occurs in our application. It includes a title for the error, massage, and a status code, providing the client with useful information about what went wrong.</p>
<p>Let's define another model to manage our database connection string.</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Models/DbSettings.cs </span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">TodoAPI.Models</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">DbSettings</span>
    {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> ConnectionString { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    }
}
</code></pre>
<p>The <code>DbSettings</code> model is designed to encapsulate the connection string for our database. It contains a single property, <code>ConnectionString</code>, which will store the actual connection string value.</p>
<p>With our <code>Todo</code> model in place, we're now ready to proceed with setting up the database context.</p>
<p>Before we begin setting up our database, we need to install the necessary packages for our project.</p>
<h3 id="heading-package-installation">   Package Installation </h3>


<p>To set up our project, we need to install several packages. We'll use the dotnet CLI for this task. </p>
<p>Before we begin, ensure you're in the root directory of your project. If you're unsure of your current location in the terminal, you can verify it by running the following command:</p>
<pre><code class="lang-bash">ls
</code></pre>
<p>This command will list all the files and folders in your current directory. The image below shows the terminal output after running the <code>ls</code> command.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/ls-terminal.png" alt="Terminal ls file" width="600" height="400" loading="lazy"></p>
<p>If your terminal output matches the image above, you're in the correct directory to install the packages.</p>
<p>Now, let's install the packages:</p>
<pre><code class="lang-bash">dotnet add package Microsoft.EntityFrameworkCore --version 8.0.0 
dotnet add package Microsoft.EntityFrameworkCore.Design --version 8.0.0
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 8.0.0
dotnet add package AutoMapper --version 13.0.1
</code></pre>
<p>Here's a brief overview of what these packages do:</p>
<ul>
<li><code>Microsoft.EntityFrameworkCore</code>: Provides the core Entity Framework Core functionality, enabling us to interact with our database.</li>
<li><code>Microsoft.EntityFrameworkCore.Design</code>: Includes design-time components for Entity Framework Core, such as migrations.</li>
<li><code>Microsoft.EntityFrameworkCore.SqlServer</code>: Allows us to use SQL Server as our database provider.</li>
<li><code>AutoMapper</code>: Simplifies object-to-object mapping, making it easier to map properties between different objects.</li>
</ul>
<p><strong>Note</strong>: Ensure you install the same versions of the packages as shown above to avoid any compatibility issues.</p>
<p>To confirm that all the packages have been installed successfully, navigate to the <code>TodoAPI.csproj</code> file located in the root directory of your project. The installed packages should be listed under the <code>ItemGroup</code> section.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">Project</span> <span class="hljs-attr">Sdk</span>=<span class="hljs-string">"Microsoft.NET.Sdk.Web"</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">PropertyGroup</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">TargetFramework</span>&gt;</span>net8.0<span class="hljs-tag">&lt;/<span class="hljs-name">TargetFramework</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Nullable</span>&gt;</span>enable<span class="hljs-tag">&lt;/<span class="hljs-name">Nullable</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">ImplicitUsings</span>&gt;</span>enable<span class="hljs-tag">&lt;/<span class="hljs-name">ImplicitUsings</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">InvariantGlobalization</span>&gt;</span>true<span class="hljs-tag">&lt;/<span class="hljs-name">InvariantGlobalization</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">PropertyGroup</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">ItemGroup</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">PackageReference</span> <span class="hljs-attr">Include</span>=<span class="hljs-string">"AutoMapper"</span> <span class="hljs-attr">Version</span>=<span class="hljs-string">"13.0.1"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">PackageReference</span> <span class="hljs-attr">Include</span>=<span class="hljs-string">"Microsoft.AspNetCore.OpenApi"</span> <span class="hljs-attr">Version</span>=<span class="hljs-string">"8.0.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">PackageReference</span> <span class="hljs-attr">Include</span>=<span class="hljs-string">"Microsoft.EntityFrameworkCore"</span> <span class="hljs-attr">Version</span>=<span class="hljs-string">"8.0.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">PackageReference</span> <span class="hljs-attr">Include</span>=<span class="hljs-string">"Microsoft.EntityFrameworkCore.Design"</span> <span class="hljs-attr">Version</span>=<span class="hljs-string">"8.0.0"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">IncludeAssets</span>&gt;</span>runtime; build; native; contentfiles; analyzers; buildtransitive<span class="hljs-tag">&lt;/<span class="hljs-name">IncludeAssets</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">PrivateAssets</span>&gt;</span>all<span class="hljs-tag">&lt;/<span class="hljs-name">PrivateAssets</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">PackageReference</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">PackageReference</span> <span class="hljs-attr">Include</span>=<span class="hljs-string">"Microsoft.EntityFrameworkCore.SqlServer"</span> <span class="hljs-attr">Version</span>=<span class="hljs-string">"8.0.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">PackageReference</span> <span class="hljs-attr">Include</span>=<span class="hljs-string">"Swashbuckle.AspNetCore"</span> <span class="hljs-attr">Version</span>=<span class="hljs-string">"6.4.0"</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">ItemGroup</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">Project</span>&gt;</span>
</code></pre>
<p>The above <code>TodoAPI.csproj</code> file shows the installed packages listed under the <code>ItemGroup</code> section. If your <code>TodoAPI.csproj</code> file reflects the same, it confirms that the packages have been installed successfully.</p>
<p>With the necessary packages installed, we're now ready to set up the database context for our Todo API.</p>
<h2 id="step-4">  Step 4: Set Up the Database Context  </h2>

<p>In ASP.NET Core, the database context is a crucial component that manages interactions with the database. It's responsible for tasks such as establishing a connection to the database, querying data, and saving changes. </p>
<p>To enable our <code>Todo API</code> to interact with the database, we need to create a database context.</p>
<p>Let's create a new file named <code>TodoDbContext</code> in the <code>AppDataContext</code> folder and populate it with the following code:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// AppDataContext/TodoDbContext.cs</span>

<span class="hljs-keyword">using</span> Microsoft.EntityFrameworkCore;
<span class="hljs-keyword">using</span> Microsoft.Extensions.Options;
<span class="hljs-keyword">using</span> TodoAPI.Models;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">TodoAPI.AppDataContext</span>
{

    <span class="hljs-comment">// TodoDbContext class inherits from DbContext</span>
     <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TodoDbContext</span> : <span class="hljs-title">DbContext</span>
     {

        <span class="hljs-comment">// DbSettings field to store the connection string</span>
         <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> DbSettings _dbsettings;

            <span class="hljs-comment">// Constructor to inject the DbSettings model</span>
         <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">TodoDbContext</span>(<span class="hljs-params">IOptions&lt;DbSettings&gt; dbSettings</span>)</span>
         {
             _dbsettings = dbSettings.Value;
         }


        <span class="hljs-comment">// DbSet property to represent the Todo table</span>
         <span class="hljs-keyword">public</span> DbSet&lt;Todo&gt; Todos { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

         <span class="hljs-comment">// Configuring the database provider and connection string</span>

         <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">OnConfiguring</span>(<span class="hljs-params">DbContextOptionsBuilder optionsBuilder</span>)</span>
         {
             optionsBuilder.UseSqlServer(_dbsettings.ConnectionString);
         }

            <span class="hljs-comment">// Configuring the model for the Todo entity</span>
         <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">OnModelCreating</span>(<span class="hljs-params">ModelBuilder modelBuilder</span>)</span>
         {
             modelBuilder.Entity&lt;Todo&gt;()
                 .ToTable(<span class="hljs-string">"TodoAPI"</span>)
                 .HasKey(x =&gt; x.id);
         }
     }
}
</code></pre>
<p>Here's a breakdown of the <code>TodoDbContext</code> class:</p>
<ul>
<li><strong><code>TodoDbContext</code></strong>: This class, which inherits from <code>DbContext</code> (a part of Entity Framework Core), is the primary class that interacts with the database.</li>
<li><strong><code>_dbsettings</code></strong>: This private field stores the connection string for our database. We inject the <code>DbSettings</code> model, which we created earlier to manage the connection string, into the <code>TodoDbContext</code> class.</li>
<li><strong><code>Todos</code></strong>: This property represents the <code>Todo</code> table in our database. It's a <code>DbSet</code> of <code>Todo</code> objects, which allows us to query and save instances of <code>Todo</code>.</li>
<li><strong><code>OnConfiguring</code></strong>: This method configures the database provider and connection string. We're using SQL Server as our database provider, and the connection string is retrieved from the <code>DbSettings</code> model.</li>
<li><strong><code>OnModelCreating</code></strong>: This method configures the model for the <code>Todo</code> entity. We specify the table name, primary key, and other configurations for the <code>Todo</code> entity.</li>
</ul>
<p>To use our <code>TodoDbContext</code> for interacting with the database, we need to register it in the <code>Program.cs</code> file. This registration process is part of setting up the Dependency Injection (DI) container in .NET Core.</p>
<p>Here's how to do it:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Program.cs</span>


<span class="hljs-keyword">using</span> TodoAPI.AppDataContext;
<span class="hljs-keyword">using</span> TodoAPI.Models;

<span class="hljs-keyword">var</span> builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();



 <span class="hljs-comment">// Add  This to in the Program.cs file</span>
builder.Services.Configure&lt;DbSettings&gt;(builder.Configuration.GetSection(<span class="hljs-string">"DbSettings"</span>)); <span class="hljs-comment">// Add this line</span>
builder.Services.AddSingleton&lt;TodoDbContext&gt;(); <span class="hljs-comment">// Add this line</span>




<span class="hljs-keyword">var</span> app = builder.Build();

<span class="hljs-comment">// Add this line</span>

{
    <span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> scope = app.Services.CreateScope(); <span class="hljs-comment">// Add this line</span>
    <span class="hljs-keyword">var</span> context = scope.ServiceProvider; <span class="hljs-comment">// Add this line</span>
}


<span class="hljs-keyword">if</span> (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseExceptionHandler();
app.UseAuthorization();

app.MapControllers();

app.Run();
</code></pre>
<p>In the code snippet above, we're doing two things:</p>
<ul>
<li>Configuring the database settings by binding the <code>DbSettings</code> section from the <code>appsettings.json</code> file to the <code>DbSettings</code> class. This allows us to access the database connection string in our application.</li>
<li>Registering the <code>TodoDbContext</code> with the DI container as a singleton service. This means that a single instance of <code>TodoDbContext</code> will be created and shared across the entire application.</li>
</ul>
<p>With the database context registered, we can now use it to perform CRUD operations on our Todo items.</p>
<p>Now let's check if everything is working fine by running the application.</p>
<pre><code class="lang-bash">
dotnet run
</code></pre>
<p>If you see the following output, it means your application is running successfully:</p>
<pre><code class="lang-bash">
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5086
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: E:\Todo\TodoAPI
</code></pre>
<p><strong>Note</strong>: If you encounter any errors, just make sure you've followed all the steps correctly and that the necessary packages have been installed successfully. If you see some warnings, you can ignore them for now.</p>
<p>With the <code>TodoDbContext</code> class now set up, we're ready to define the Contracts  for our application.</p>
<h2 id="step-5">  Step 5: Define Data Transfer Objects (DTOs) </h2>

<p>In the context of .NET development, a Data Transfer Object (DTO) is a simple object that carries data between processes. It's often used in conjunction with a service layer to shape the data sent between the client and the server. </p>
<p>For our Todo API, we'll define two DTOs: <code>CreateTodoRequest</code> and <code>UpdateTodoRequest</code>. These DTOs will help us enforce the structure and validation of the data sent to our API.</p>
<p>Navigate to the <code>Contracts</code> folder and create two new files: <code>CreateTodoRequest.cs</code> and <code>UpdateTodoRequest.cs</code>.</p>
<h3 id="heading-the-createtodorequest-file"> The <code>CreateTodoRequest</code> File </h3>


<p>The <code>CreateTodoRequest</code> DTO will define the structure and validation rules for creating a new Todo item. Add the following code to the <code>CreateTodoRequest.cs</code> file:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CreateTodoRequest</span>
{
    [<span class="hljs-meta">Required</span>]
    [<span class="hljs-meta">StringLength(100)</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Title { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    [<span class="hljs-meta">StringLength(500)</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Description { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    [<span class="hljs-meta">Required</span>]
    <span class="hljs-keyword">public</span> DateTime DueDate { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    [<span class="hljs-meta">Range(1, 5)</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Priority { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre>
<p>In this DTO, we've defined properties for <code>Title</code>, <code>Description</code>, <code>DueDate</code>, and <code>Priority</code>. We've also added validation attributes like <code>[Required]</code>, <code>[StringLength]</code>, and <code>[Range]</code> to enforce certain rules on these properties.</p>
<h3 id="heading-the-updatetodorequest-file"> The <code>UpdateTodoRequest</code> File </h3>


<p>The <code>UpdateTodoRequest</code> DTO will define the structure and validation rules for updating an existing Todo item. Add the following code to the <code>UpdateTodoRequest.cs</code> file:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">UpdateTodoRequest</span>
{
    [<span class="hljs-meta">StringLength(100)</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Title { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    [<span class="hljs-meta">StringLength(500)</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Description { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span>? IsComplete { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-keyword">public</span> DateTime? DueDate { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    [<span class="hljs-meta">Range(1, 5)</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span>? Priority { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">UpdateTodoRequest</span>(<span class="hljs-params"></span>)</span>
    {
        IsComplete = <span class="hljs-literal">false</span>;
    }
}
</code></pre>
<p>In this DTO, we've defined properties for <code>Title</code>, <code>Description</code>, <code>IsComplete</code>, <code>DueDate</code>, and <code>Priority</code>. The <code>IsComplete</code> property is nullable, which means it can be set to <code>null</code> if not provided. We've also added validation attributes like <code>[StringLength]</code> and <code>[Range]</code> to enforce certain rules on these properties.</p>
<p>With these DTOs in place, we're now ready to implement the service layer for our Todo API.</p>
<p>Now test the application, and see if there are any errors.</p>
<pre><code class="lang-bash">
 dotnet  build
</code></pre>
<p>If you see the following output, it means your application is running successfully:</p>
<pre><code class="lang-bash">MSBuild version 17.8.3+195e7f5a3 <span class="hljs-keyword">for</span> .NET
  Determining projects to restore...
  All projects are up-to-date <span class="hljs-keyword">for</span> restore.
  TodoAPI -&gt; E:\Todo\TodoAPI\bin\Debug\net8.0\TodoAPI.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:00.94
</code></pre>
<p><strong>Note</strong>: If you encounter any errors, make sure you've followed all the steps correctly and that the necessary packages have been installed successfully. If you see some warnings, you can ignore them for now.</p>
<p>With the DTOs defined, we're now ready to implement the Mapping for the   Todo API.</p>
<h2 id="step-6">  Step 6: Implement Object Mapping for the Todo API </h2>

<p>Having defined the DTOs for our Todo API, the next step is to implement object mapping. This process allows us to convert between the DTOs and the Todo model, a critical aspect of data transformation in our application.</p>
<p>To streamline this process, we'll use the <code>AutoMapper</code> library. AutoMapper is a widely-used library that simplifies object-to-object mapping, making it easier to map properties between different objects.</p>
<p>We've already installed the <code>AutoMapper</code> package in our project. Now, in the <code>MappingProfiles</code> folder, create a new file named <code>AutoMapperProfile.cs</code> and add the following code:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> AutoMapper;
<span class="hljs-keyword">using</span> TodoAPI.Contracts;
<span class="hljs-keyword">using</span> TodoAPI.Models;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">TodoAPI.MappingProfiles</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">AutoMapperProfile</span> : <span class="hljs-title">Profile</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">AutoMapperProfile</span>(<span class="hljs-params"></span>)</span>
        {
            CreateMap&lt;CreateTodoRequest, Todo&gt;()
                .ForMember(dest =&gt; dest.id, opt =&gt; opt.Ignore())
                .ForMember(dest =&gt; dest.CreatedAt, opt =&gt; opt.Ignore())
                .ForMember(dest =&gt; dest.UpdatedAt, opt =&gt; opt.Ignore());

            CreateMap&lt;UpdateTodoRequest, Todo&gt;()
                .ForMember(dest =&gt; dest.id, opt =&gt; opt.Ignore())
                .ForMember(dest =&gt; dest.CreatedAt, opt =&gt; opt.Ignore())
                .ForMember(dest =&gt; dest.UpdatedAt, opt =&gt; opt.Ignore());
        }
    }
}
</code></pre>
<p>Let's break down the <code>AutoMapperProfile</code> class:</p>
<ul>
<li><strong>AutoMapperProfile</strong>: This class, which inherits from <code>Profile</code> (a class provided by AutoMapper), allows us to define mapping configurations.</li>
<li><strong>CreateMap</strong>: This method creates a mapping between two objects. Here, we're mapping from <code>CreateTodoRequest</code> to <code>Todo</code> and from <code>UpdateTodoRequest</code> to <code>Todo</code>.</li>
<li><strong>ForMember</strong>: This method configures the mapping for a specific property. We're using it to ignore the <code>id</code>, <code>CreatedAt</code>, and <code>UpdatedAt</code> properties when mapping from the DTOs to the <code>Todo</code> model.</li>
</ul>
<p>Now let's add the automapper to the DI container in the <code>Program.cs</code> file.</p>
<pre><code class="lang-csharp">
<span class="hljs-comment">// Program.cs</span>

<span class="hljs-keyword">using</span> TodoAPI.AppDataContext;
<span class="hljs-keyword">using</span> TodoAPI.Models;

<span class="hljs-keyword">var</span> builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();



 <span class="hljs-comment">// Add  This to in the Program.cs file</span>
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());  <span class="hljs-comment">// Add this line</span>


<span class="hljs-comment">// .....</span>

<span class="hljs-keyword">var</span> app = builder.Build();



<span class="hljs-comment">// .....</span>
<span class="hljs-keyword">if</span> (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseExceptionHandler();
app.UseAuthorization();

app.MapControllers();

app.Run();
</code></pre>
<p>With the mapping profiles in place, we can now implement the service layer for our Todo API.</p>
<h2 id="step-7"> Step 7: Implement Global Exception Handling Middleware </h2>

<p>As we progress with our Todo API, it's crucial to implement a mechanism for handling exceptions globally. This ensures that any exceptions that occur during the execution of our application are caught and handled appropriately, providing meaningful error messages to the client.</p>
<p>.NET 8 introduces the <code>IExceptionHandler</code> interface, which simplifies the process of creating a custom exception handler. This handler will catch all exceptions that occur in our application and return a consistent error response to the client.</p>
<p>Let's create a global exception handler in the <code>Middleware</code> folder. Create a new file named <code>GlobalExceptionHandler.cs</code> and add the following code:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Middleware/GlobalExceptionHandler.cs</span>

<span class="hljs-keyword">using</span> System.Net;
<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Diagnostics;
<span class="hljs-keyword">using</span> TodoAPI.Models;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">TodoAPI.Middleware</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">GlobalExceptionHandler</span> : <span class="hljs-title">IExceptionHandler</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> ILogger&lt;GlobalExceptionHandler&gt; _logger;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">GlobalExceptionHandler</span>(<span class="hljs-params">ILogger&lt;GlobalExceptionHandler&gt; logger</span>)</span>
        {
            _logger = logger;
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> ValueTask&lt;<span class="hljs-keyword">bool</span>&gt; <span class="hljs-title">TryHandleAsync</span>(<span class="hljs-params">
            HttpContext httpContext,
            Exception exception,
            CancellationToken cancellationToken</span>)</span>
        {
            _logger.LogError(
                <span class="hljs-string">$"An error occurred while processing your request: <span class="hljs-subst">{exception.Message}</span>"</span>);

            <span class="hljs-keyword">var</span> errorResponse = <span class="hljs-keyword">new</span> ErrorResponse
            {
                Message = exception.Message
            };

            <span class="hljs-keyword">switch</span> (exception)
            {
                <span class="hljs-keyword">case</span> BadHttpRequestException:
                    errorResponse.StatusCode = (<span class="hljs-keyword">int</span>)HttpStatusCode.BadRequest;
                    errorResponse.Title = exception.GetType().Name;
                    <span class="hljs-keyword">break</span>;

                <span class="hljs-keyword">default</span>:
                    errorResponse.StatusCode = (<span class="hljs-keyword">int</span>)HttpStatusCode.InternalServerError;
                    errorResponse.Title = <span class="hljs-string">"Internal Server Error"</span>;
                    <span class="hljs-keyword">break</span>;
            }

            httpContext.Response.StatusCode = errorResponse.StatusCode;

            <span class="hljs-keyword">await</span> httpContext
                .Response
                .WriteAsJsonAsync(errorResponse, cancellationToken);

            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
        }
    }
}
</code></pre>
<p>Here's a breakdown of the <code>GlobalExceptionHandler</code> class:</p>
<ul>
<li><strong>GlobalExceptionHandler</strong>: This class implements the <code>IExceptionHandler</code> interface, enabling global exception handling in our application.</li>
<li><strong>TryHandleAsync</strong>: This method is invoked when an exception occurs. It logs the error message, creates an <code>ErrorResponse</code> object, sets the status code and title based on the exception type, and returns a consistent error response to the client.</li>
<li><strong>ErrorResponse</strong>: This class represents the error response returned to the client when an exception occurs. It contains properties for the error message, status code, and title.</li>
<li><strong>BadHttpRequestException</strong>: This case handles exceptions of type <code>BadHttpRequestException</code> and sets the status code and title accordingly.</li>
</ul>
<p>After setting up the global exception handler, we need to register it in our <code>Program.cs</code> file:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Program.cs</span>

<span class="hljs-keyword">using</span> TodoAPI.AppDataContext;
<span class="hljs-keyword">using</span> TodoAPI.Interface;
<span class="hljs-keyword">using</span> TodoAPI.Middleware;
<span class="hljs-keyword">using</span> TodoAPI.Models;
<span class="hljs-keyword">using</span> TodoAPI.Services;

<span class="hljs-keyword">var</span> builder = WebApplication.CreateBuilder(args);



builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();



<span class="hljs-comment">// ....</span>



builder.Services.AddExceptionHandler&lt;GlobalExceptionHandler&gt;(); <span class="hljs-comment">// Add this line</span>

builder.Services.AddProblemDetails();  <span class="hljs-comment">// Add this line</span>

<span class="hljs-comment">// Adding of login </span>
builder.Services.AddLogging();  <span class="hljs-comment">//  Add this line</span>



<span class="hljs-keyword">var</span> app = builder.Build();


<span class="hljs-comment">// ......</span>


<span class="hljs-keyword">if</span> (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection(); <span class="hljs-comment">// Add this line</span>

app.UseExceptionHandler();
app.UseAuthorization();

app.MapControllers();

app.Run();


<span class="hljs-comment">// ...</span>
</code></pre>
<h2 id="step-8"> Step 8: Implement the Service Layer and Service Interface </h2>

<p>In .NET development, the service layer encapsulates the core business logic of an application. It serves as a bridge between the controller and the database, ensuring a clean separation of concerns.</p>
<p>First, let's define an interface for our service layer.</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Interfaces/ITodoServices.cs </span>

<span class="hljs-keyword">using</span> TodoAPI.Contracts;
<span class="hljs-keyword">using</span> TodoAPI.Models;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">TodoAPI.Interface</span>
{
     <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">ITodoServices</span>
     {
         Task&lt;IEnumerable&lt;Todo&gt;&gt; GetAllAsync();
         <span class="hljs-function">Task&lt;Todo&gt; <span class="hljs-title">GetByIdAsync</span>(<span class="hljs-params">Guid id</span>)</span>;
         <span class="hljs-function">Task <span class="hljs-title">CreateTodoAsync</span>(<span class="hljs-params">CreateTodoRequest request</span>)</span>;
         <span class="hljs-function">Task <span class="hljs-title">UpdateTodoAsync</span>(<span class="hljs-params">Guid id, UpdateTodoRequest request</span>)</span>;
         <span class="hljs-function">Task <span class="hljs-title">DeleteTodoAsync</span>(<span class="hljs-params">Guid id</span>)</span>;
     }
}
</code></pre>
<p>Here's a brief overview of the methods defined in the <code>ITodoServices</code> interface:</p>
<ul>
<li><code>GetAllAsync</code>: Retrieves all Todo items from the database.</li>
<li><code>GetByIdAsync</code>: Fetches a specific Todo item by its <code>Id</code>.</li>
<li><code>CreateTodoAsync</code>: Adds a new Todo item to the database.</li>
<li><code>UpdateTodoAsync</code>: Modifies an existing Todo item in the database.</li>
<li><code>DeleteTodoAsync</code>: Removes a Todo item from the database.</li>
</ul>
<p>Now, let's create a service class that implements these methods. We'll use Dependency Injection to inject the <code>ITodoServices</code> interface into the service class, making our code more modular, testable, and maintainable.</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Services/TodoServices.cs</span>

<span class="hljs-keyword">using</span> TodoAPI.Interface;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">TodoAPI.Services</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TodoServices</span> : <span class="hljs-title">ITodoServices</span>
    {

    }
}
</code></pre>
<p>At this point, you'll encounter an error because we haven't implemented the methods from the <code>ITodoServices</code> interface in the <code>TodoServices</code> class. </p>
<p>The below image shows the error message that appears when the methods from the <code>ITodoServices</code> interface are not implemented in the <code>TodoServices</code> class.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/InterfaceError.png" alt="Error in the TodoServices class" width="600" height="400" loading="lazy"></p>
<p>To resolve this, hover over <code>ITodoServices</code>, click on the light bulb icon that appears, and select 'Implement interface'. This will automatically generate stubs for the methods defined in the <code>ITodoServices</code> interface.</p>
<p>The below image shows the 'Implement interface' option that appears when hovering over <code>ITodoServices</code> in the <code>TodoServices</code> class.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/QickFixt.png" alt="Implementing the ITodoServices interface" width="600" height="400" loading="lazy"></p>
<p>After implementing the interface, the <code>TodoServices</code> class should look like this:</p>
<pre><code class="lang-csharp">

<span class="hljs-comment">// Services/TodoServices.cs</span>
<span class="hljs-keyword">using</span> TodoAPI.Contracts;
<span class="hljs-keyword">using</span> TodoAPI.Interface;
<span class="hljs-keyword">using</span> TodoAPI.Models;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">TodoAPI.Services</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TodoServices</span> : <span class="hljs-title">ITodoServices</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> Task <span class="hljs-title">CreateTodoAsync</span>(<span class="hljs-params">CreateTodoRequest request</span>)</span>
        {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotImplementedException();
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> Task <span class="hljs-title">DeleteTodoAsync</span>(<span class="hljs-params">Guid id</span>)</span>
        {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotImplementedException();
        }

        <span class="hljs-keyword">public</span> Task&lt;IEnumerable&lt;Todo&gt;&gt; GetAllAsync()
        {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotImplementedException();
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> Task&lt;Todo&gt; <span class="hljs-title">GetByIdAsync</span>(<span class="hljs-params">Guid id</span>)</span>
        {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotImplementedException();
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> Task <span class="hljs-title">UpdateTodoAsync</span>(<span class="hljs-params">Guid id, UpdateTodoRequest request</span>)</span>
        {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotImplementedException();
        }
    }
}
</code></pre>
<h3 id="heading-how-to-enhance-the-todoservices-class-with-dependency-injection"> How to Enhance the TodoServices Class with Dependency Injection </h3>

<p>Now, let's enrich our <code>TodoServices</code> class with some essential properties. These properties will provide the necessary tools for interacting with the database, logging, and object mapping.</p>
<p>At the top of the <code>TodoServices</code> class, add the following properties:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Services/TodoServices.cs</span>

<span class="hljs-comment">// ...</span>

<span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> TodoDbContext _context;
<span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> ILogger&lt;TodoServices&gt; _logger;
<span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IMapper _mapper;

<span class="hljs-comment">// ...</span>
</code></pre>
<p>Here's a brief explanation of these properties:</p>
<ul>
<li><code>_context</code>: An instance of the <code>TodoDbContext</code> class, enabling us to interact with the database.</li>
<li><code>_logger</code>: An instance of the <code>ILogger</code> class, facilitating logging throughout our application.</li>
<li><code>_mapper</code>: An instance of the <code>IMapper</code> class, allowing us to perform object-to-object mapping using AutoMapper.</li>
</ul>
<p>Next, we'll update the constructor of the <code>TodoServices</code> class to inject these dependencies:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Services/TodoServices.cs</span>

<span class="hljs-comment">// ...</span>

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">TodoServices</span>(<span class="hljs-params">TodoDbContext context, ILogger&lt;TodoServices&gt; logger, IMapper mapper</span>)</span>
{
    _context = context;
    _logger = logger;
    _mapper = mapper;
}

<span class="hljs-comment">// ...</span>
</code></pre>
<p>With these dependencies injected, we're now ready to implement the methods defined in the <code>ITodoServices</code> interface. We'll begin with the <code>GetAllAsync</code> method in the next section.</p>
<h2 id="step-9"> Step 9: Implement the CreateTodoAsync Method in the TodoServices Class </h2>

<p>Now, let's implement the <code>CreateTodoAsync</code> method in the <code>TodoServices</code> class. This method will handle the creation of new Todo items in our database.</p>
<p>Navigate to the <code>TodoServices</code> class and add the following code to the <code>CreateTodoAsync</code> method:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Services/TodoServices.cs</span>

<span class="hljs-comment">// ...</span>

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">CreateTodoAsync</span>(<span class="hljs-params">CreateTodoRequest request</span>)</span>
{
    <span class="hljs-keyword">try</span>
    {
        <span class="hljs-keyword">var</span> todo = _mapper.Map&lt;Todo&gt;(request);
        todo.CreatedAt = DateTime.UtcNow;
        _context.Todos.Add(todo);
        <span class="hljs-keyword">await</span> _context.SaveChangesAsync();
    }
    <span class="hljs-keyword">catch</span> (Exception ex)
    {
        _logger.LogError(ex, <span class="hljs-string">"An error occurred while creating the Todo item."</span>);
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Exception(<span class="hljs-string">"An error occurred while creating the Todo item."</span>);
    }
}

<span class="hljs-comment">// ...</span>
</code></pre>
<p>Here's a breakdown of the <code>CreateTodoAsync</code> method:</p>
<ul>
<li><strong>Mapping</strong>: We use AutoMapper to convert the <code>CreateTodoRequest</code> object into a <code>Todo</code> entity.</li>
<li><strong>CreatedAt</strong>: We set the <code>CreatedAt</code> property of the <code>Todo</code> entity to the current UTC date and time.</li>
<li><strong>Adding to the Database</strong>: We add the <code>Todo</code> entity to the <code>Todos</code> DbSet in our context and save the changes asynchronously.</li>
<li><strong>Error Handling</strong>: We catch any exceptions that might occur during the process, log the error, and throw a new exception with a descriptive error message.</li>
</ul>
<p>With the <code>CreateTodoAsync</code> method implemented, we can now create new Todo items in our database.</p>
<h2 id="step-10"> Step 10: Implement the GetAllAsync Method in the Service Class </h2>

<p>Next, let's implement the <code>GetAllAsync</code> method in the <code>TodoServices</code> class. This method will retrieve all Todo items from the database.</p>
<p>Navigate to the <code>TodoServices</code> class and add the following code to the <code>GetAllAsync</code> method:</p>
<pre><code class="lang-csharp">

<span class="hljs-comment">// Services/TodoServices.cs</span>

<span class="hljs-comment">// ...</span>


 <span class="hljs-comment">// Get all TODO Items from the database </span>
 <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IEnumerable&lt;Todo&gt;&gt; GetAllAsync()
 {
     <span class="hljs-keyword">var</span> todo= <span class="hljs-keyword">await</span> _context.Todos.ToListAsync();
     <span class="hljs-keyword">if</span> (todo == <span class="hljs-literal">null</span>)
     {
         <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Exception(<span class="hljs-string">" No Todo items found"</span>);
     }
     <span class="hljs-keyword">return</span> todo;

 }

<span class="hljs-comment">// ...</span>
</code></pre>
<p>Here's a breakdown of the <code>GetAllAsync</code> method:</p>
<ul>
<li><p><strong>Retrieving Todo Items</strong>: We use Entity Framework Core's <code>ToListAsync</code> method to fetch all Todo items from the database.</p>
</li>
<li><p><strong>Error Handling</strong>: If no Todo items are found, we throw an exception with a descriptive error message.</p>
</li>
</ul>
<p>Now Your Service class should look like this:</p>
<pre><code class="lang-csharp">


<span class="hljs-keyword">using</span> AutoMapper;
<span class="hljs-keyword">using</span> Microsoft.EntityFrameworkCore;
<span class="hljs-keyword">using</span> TodoAPI.AppDataContext;
<span class="hljs-keyword">using</span> TodoAPI.Contracts;
<span class="hljs-keyword">using</span> TodoAPI.Interface;
<span class="hljs-keyword">using</span> TodoAPI.Models;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">TodoAPI.Services</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TodoServices</span> : <span class="hljs-title">ITodoServices</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> TodoDbContext _context;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> ILogger&lt;TodoServices&gt; _logger;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IMapper _mapper;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">TodoServices</span>(<span class="hljs-params">TodoDbContext context, ILogger&lt;TodoServices&gt; logger, IMapper mapper</span>)</span>
        {
            _context = context;
            _logger = logger;
            _mapper = mapper;
        }




        <span class="hljs-comment">//  Create Todo for it be save in the datbase </span>

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">CreateTodoAsync</span>(<span class="hljs-params">CreateTodoRequest request</span>)</span>
        {
            <span class="hljs-keyword">try</span>
            {
                <span class="hljs-keyword">var</span> todo = _mapper.Map&lt;Todo&gt;(request);
                todo.CreatedAt = DateTime.Now;
                _context.Todos.Add(todo);
                <span class="hljs-keyword">await</span> _context.SaveChangesAsync();
            }
            <span class="hljs-keyword">catch</span> (Exception ex)
            {
                _logger.LogError(ex, <span class="hljs-string">"An error occurred while creating the todo item."</span>);
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Exception(<span class="hljs-string">"An error occurred while creating the todo item."</span>);
            }
        }

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IEnumerable&lt;Todo&gt;&gt; GetAllAsync()
        {
            <span class="hljs-keyword">var</span> todo = <span class="hljs-keyword">await</span> _context.Todos.ToListAsync();
            <span class="hljs-keyword">if</span> (todo == <span class="hljs-literal">null</span>)
            {
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Exception(<span class="hljs-string">" No Todo items found"</span>);
            }
            <span class="hljs-keyword">return</span> todo;

        }
        <span class="hljs-function"><span class="hljs-keyword">public</span> Task <span class="hljs-title">DeleteTodoAsync</span>(<span class="hljs-params">Guid id</span>)</span>
        {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotImplementedException();
        }

        <span class="hljs-comment">// Get all TODO Items from the database </span>


        <span class="hljs-function"><span class="hljs-keyword">public</span> Task&lt;Todo&gt; <span class="hljs-title">GetByIdAsync</span>(<span class="hljs-params">Guid id</span>)</span>
        {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotImplementedException();
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> Task <span class="hljs-title">UpdateTodoAsync</span>(<span class="hljs-params">Guid id, UpdateTodoRequest request</span>)</span>
        {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotImplementedException();
        }
    }
}
</code></pre>
<p>Now we have implemented the <code>CreateTodoAsync</code> and <code>GetAllAsync</code> methods in the <code>TodoServices</code> class. Before we proceed to implement the remaining methods, let's create routes for our API in the Controllers folder. So now let's create the TodoController class.</p>
<h2 id="step-11"> Step 11: Create the TodoController Class  </h2>

<p>In ASP.NET Core, controllers are responsible for handling incoming HTTP requests and sending responses. They serve as the entry point for our API, defining the routes and actions that clients can interact with.</p>
<p>Let's create a new file named <code>TodoController.cs</code> in the <code>Controllers</code> folder and add the following code:</p>
<pre><code class="lang-csharp">

<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Mvc;
<span class="hljs-keyword">using</span> TodoAPI.Interface;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">TodoAPI.Controllers</span>
{
    [<span class="hljs-meta">ApiController</span>]
    [<span class="hljs-meta">Route(<span class="hljs-meta-string">"api/[controller]"</span>)</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TodoController</span> : <span class="hljs-title">ControllerBase</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> ITodoServices _todoServices;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">TodoController</span>(<span class="hljs-params">ITodoServices todoServices</span>)</span>
        {
            _todoServices = todoServices;
        }

    }
}
</code></pre>
<p>The <code>TodoController</code> class inherits from <code>ControllerBase</code>, a base class provided by ASP.NET Core for creating controllers. We've also added a route prefix of <code>api/[controller]</code> to the controller, which will be used as the base route for all actions in the controller.</p>
<h2 id="step-12"> Step 12: Implement the CreateTodoAsync  Method in the TodoController Class  </h2>

<p>Now that we have our Controller class, let's implement the <code>CreateTodoAsync</code> method in the <code>TodoController</code> class. This method will handle the creation of new Todo items in our database.</p>
<p>Navigate to the <code>TodoController</code> class and add the following code to the <code>CreateTodoAsync</code> method:</p>
<pre><code class="lang-csharp">
<span class="hljs-comment">// Controllers/TodoController.cs</span>

<span class="hljs-comment">// ...</span>
  [<span class="hljs-meta">HttpPost</span>]
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IActionResult&gt; <span class="hljs-title">CreateTodoAsync</span>(<span class="hljs-params">CreateTodoRequest request</span>)</span>
  {
      <span class="hljs-keyword">if</span> (!ModelState.IsValid)
      {
          <span class="hljs-keyword">return</span> BadRequest(ModelState);
      }


      <span class="hljs-keyword">try</span>
      {

          <span class="hljs-keyword">await</span> _todoServices.CreateTodoAsync(request);
          <span class="hljs-keyword">return</span> Ok(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">"Blog post successfully created"</span> });

      }
      <span class="hljs-keyword">catch</span> (Exception ex)
      {
          <span class="hljs-keyword">return</span> StatusCode(<span class="hljs-number">500</span>, <span class="hljs-keyword">new</span> { message = <span class="hljs-string">"An error occurred while creating the  crating Todo Item"</span>, error = ex.Message });

      }
  }
  <span class="hljs-comment">// ...</span>
</code></pre>
<p>Here's a breakdown of the <code>CreateTodoAsync</code> method:</p>
<ul>
<li><p><strong>Model Validation</strong>: We check if the request model is valid using <code>ModelState.IsValid</code>. If the model is not valid, we return a <code>BadRequest</code> response with the model state errors.</p>
</li>
<li><p><strong>Creating a Todo Item</strong>: We call the <code>CreateTodoAsync</code> method from the <code>ITodoServices</code> interface to create a new Todo item in the database.</p>
</li>
<li><p><strong>Success Response</strong>: If the Todo item is created successfully, we return an <code>Ok</code> response with a success message.</p>
</li>
<li><p><strong>Error Handling</strong>: If an error occurs during the creation process, we return a <code>500 Internal Server Error</code> response with an error message.</p>
</li>
</ul>
<p>Now let's implement the <code>GetAllAsync</code> method in the <code>TodoController</code> class. This method will retrieve all Todo items from the database.</p>
<p>Navigate to the <code>TodoController</code> class and add the following code to the <code>GetAllAsync</code> method:</p>
<pre><code class="lang-csharp">
<span class="hljs-comment">// Controllers/TodoController.cs </span>

<span class="hljs-comment">// ...</span>

  [<span class="hljs-meta">HttpGet</span>]
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IActionResult&gt; <span class="hljs-title">GetAllAsync</span>(<span class="hljs-params"></span>)</span>
  {
      <span class="hljs-keyword">try</span>
      {
          <span class="hljs-keyword">var</span> todo = <span class="hljs-keyword">await</span> _todoServices.GetAllAsync();
          <span class="hljs-keyword">if</span> (todo == <span class="hljs-literal">null</span> || !todo.Any())
          {
              <span class="hljs-keyword">return</span> Ok(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">"No Todo Items  found"</span> });
          }
          <span class="hljs-keyword">return</span> Ok(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">"Successfully retrieved all blog posts"</span>, data = todo });

      }
      <span class="hljs-keyword">catch</span> (Exception ex)
      {
          <span class="hljs-keyword">return</span> StatusCode(<span class="hljs-number">500</span>, <span class="hljs-keyword">new</span> { message = <span class="hljs-string">"An error occurred while retrieving all Tood it posts"</span>, error = ex.Message });


      }
  }

<span class="hljs-comment">// ...</span>
</code></pre>
<p>Here's a breakdown of the <code>GetAllAsync</code> method:</p>
<ul>
<li><p><strong>Retrieving Todo Items</strong>: We call the <code>GetAllAsync</code> method from the <code>ITodoServices</code> interface to fetch all Todo items from the database.</p>
</li>
<li><p><strong>Success Response</strong>: If Todo items are retrieved successfully, we return an <code>Ok</code> response with a success message and the list of Todo items.</p>
</li>
<li><p><strong>Error Handling</strong>: If an error occurs during the retrieval process, we return a <code>500 Internal Server Error</code> response with an error message.</p>
</li>
</ul>
<p>Now your <code>TodoController</code> class should look like this:</p>
<pre><code class="lang-csharp">


<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Mvc;
<span class="hljs-keyword">using</span> TodoAPI.Contracts;
<span class="hljs-keyword">using</span> TodoAPI.Interface;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">TodoAPI.Controllers</span>
{
    [<span class="hljs-meta">ApiController</span>]
    [<span class="hljs-meta">Route(<span class="hljs-meta-string">"api/[controller]"</span>)</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TodoController</span> : <span class="hljs-title">ControllerBase</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> ITodoServices _todoServices;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">TodoController</span>(<span class="hljs-params">ITodoServices todoServices</span>)</span>
        {
            _todoServices = todoServices;
        }



<span class="hljs-comment">// Creating new Todo Item</span>
[<span class="hljs-meta">HttpPost</span>]
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IActionResult&gt; <span class="hljs-title">CreateTodoAsync</span>(<span class="hljs-params">CreateTodoRequest request</span>)</span>
  {
      <span class="hljs-keyword">if</span> (!ModelState.IsValid)
      {
          <span class="hljs-keyword">return</span> BadRequest(ModelState);
      }


      <span class="hljs-keyword">try</span>
      {

          <span class="hljs-keyword">await</span> _todoServices.CreateTodoAsync(request);
          <span class="hljs-keyword">return</span> Ok(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">"Blog post successfully created"</span> });

      }
      <span class="hljs-keyword">catch</span> (Exception ex)
      {
          <span class="hljs-keyword">return</span> StatusCode(<span class="hljs-number">500</span>, <span class="hljs-keyword">new</span> { message = <span class="hljs-string">"An error occurred while creating the  crating Todo Item"</span>, error = ex.Message });

      }
  }

    <span class="hljs-comment">// Get all Todo Items</span>

      [<span class="hljs-meta">HttpGet</span>]
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IActionResult&gt; <span class="hljs-title">GetAllAsync</span>(<span class="hljs-params"></span>)</span>
  {
      <span class="hljs-keyword">try</span>
      {
          <span class="hljs-keyword">var</span> todo = <span class="hljs-keyword">await</span> _todoServices.GetAllAsync();
          <span class="hljs-keyword">if</span> (todo == <span class="hljs-literal">null</span> || !todo.Any())
          {
              <span class="hljs-keyword">return</span> Ok(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">"No Todo Items  found"</span> });
          }
          <span class="hljs-keyword">return</span> Ok(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">"Successfully retrieved all blog posts"</span>, data = todo });

      }
      <span class="hljs-keyword">catch</span> (Exception ex)
      {
          <span class="hljs-keyword">return</span> StatusCode(<span class="hljs-number">500</span>, <span class="hljs-keyword">new</span> { message = <span class="hljs-string">"An error occurred while retrieving all Tood it posts"</span>, error = ex.Message });


      }
  }

    }
}
</code></pre>
<p>At this point, we've implemented the <code>CreateTodoAsync</code> and <code>GetAllAsync</code> methods in the <code>TodoController</code> class. These methods allow us to create new Todo items and retrieve all Todo items from the database. Let's try to run the application and see if everything is working fine.</p>
<p>Run the application by running the following command:</p>
<pre><code class="lang-bash">

dotnet run
</code></pre>
<p>If you see the following output, it means your application is running successfully:</p>
<pre><code class="lang-bash">
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5086
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: E:\Todo\TodoAPI4
</code></pre>
<p>While we'll be using Postman within Visual Studio Code for making API requests, it's worth noting that .NET 8 includes a built-in Swagger UI. This feature allows us to interact with our API endpoints directly from a web browser. To access the Swagger UI, open your browser and navigate to <code>https://localhost:5086/swagger/index.html</code>. You should see a page similar to the one below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/SwaggerUI.png" alt="SwaggerUI" width="600" height="400" loading="lazy">
This indicates that we've made significant progress. We've created an API that can create and retrieve Todo items. Let's test this by attempting to create a new Todo item using our API.</p>
<p>Open Postman and create a new POST request with the following URL: <code>https://localhost:5086/api/todo</code>. Set the request body to the following JSON object:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Learn ASP.NET Core"</span>,
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">"Learn how to build web applications with ASP.NET Core"</span>,
    <span class="hljs-attr">"dueDate"</span>: <span class="hljs-string">"2022-12-31T00:00:00"</span>,
    <span class="hljs-attr">"priority"</span>: <span class="hljs-number">5</span>
}
</code></pre>
<p>Upon executing this request, you may encounter an error. This is because we haven't yet added our connection string to the <code>appsettings.json</code> file. Let's rectify this.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/PostmanError.png" alt="PostmanError" width="600" height="400" loading="lazy"></p>
<p><strong>Note</strong>: The error above is due to the absence of a connection string in the <code>appsettings.json</code> file. Let's add the connection string to the <code>appsettings.json</code> file.</p>
<p>Before we do that, let's setup or SQL Server Database. First Open your SQL Server Management Studio and you should see the below screen:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/SQLServerManagementStudio.png" alt="SQLServerManagementStudio" width="600" height="400" loading="lazy"></p>
<p>To connect to the SQL Server, where is says <code>Server Name</code> you can type <code>localhost</code> or <code>.</code> and click on the <code>Connect</code> button.</p>
<p>After connecting to the SQL Server, you will see the following screen:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/SQLServerManagementStudio2.png" alt="SQLServerManagementStudio2" width="600" height="400" loading="lazy"></p>
<p>Now go to your <code>appsettings.json</code> file and add the following connection string:</p>
<pre><code class="lang-json">
<span class="hljs-comment">//appsettings.json</span>
{
  <span class="hljs-attr">"DbSettings"</span>: {
    <span class="hljs-attr">"ConnectionString"</span>: <span class="hljs-string">"Server=localhost;Database=TodoAPIDb;  Integrated Security=true;  TrustServerCertificate=true;"</span>
  },
  <span class="hljs-attr">"Logging"</span>: {
    <span class="hljs-attr">"LogLevel"</span>: {
      <span class="hljs-attr">"Default"</span>: <span class="hljs-string">"Information"</span>,
      <span class="hljs-attr">"Microsoft"</span>: <span class="hljs-string">"Warning"</span>,
      <span class="hljs-attr">"Microsoft.Hosting.Lifetime"</span>: <span class="hljs-string">"Information"</span>
    },
    <span class="hljs-attr">"AllowedHosts"</span>: <span class="hljs-string">"*"</span>
  }
}
</code></pre>
<p>Let me explain the connection string above:</p>
<ul>
<li><code>Server</code>: This is the server name where the database is hosted. In this case, we're using <code>localhost</code> to connect to the local SQL Server instance.</li>
<li><code>Database</code>: This is the name of the database we want to connect to. We've set it to <code>TodoAPIDb</code>.</li>
<li><code>Integrated Security</code>: This parameter specifies that we're using Windows authentication to connect to the database.</li>
<li><code>TrustServerCertificate</code>: This parameter specifies that we trust the server certificate when connecting to the database.</li>
</ul>
<p>Now we need to register our <code>Service</code> and <code>Iservices</code> in the <code>Program.cs</code> file.</p>
<p>Add the service to the <code>Program.cs</code> file:</p>
<pre><code class="lang-csharp">
<span class="hljs-comment">// Program.cs</span>

<span class="hljs-comment">// ...</span>

builder.Services.AddScoped&lt;ITodoServices, TodoServices&gt;();

<span class="hljs-comment">// ...</span>
</code></pre>
<h2 id="step-13"> Step 13: Implement Migrations and Update the Database  </h2>

<p>Migrations in Entity Framework Core provide a mechanism to keep the database schema in sync with the application's data model. They generate SQL scripts that can be applied to the database to reflect changes in the data model, eliminating the need for manual database schema updates.</p>
<p>To create a migration, ensure you're in the root directory of your project and run the following command in the terminal:</p>
<pre><code class="lang-bash">dotnet ef migrations add InitialCreate
</code></pre>
<p>Upon successful execution, you'll see an output similar to the following:</p>
<pre><code class="lang-bash">dotnet ef migrations add InitialCreate
Build started...
Build succeeded.
Done. To undo this action, use <span class="hljs-string">'ef migrations remove'</span>
</code></pre>
<p>This command generates a new migration named <code>InitialCreate</code>, which contains SQL scripts derived from the changes in our data model. A new folder named <code>Migrations</code> will appear in your project directory.</p>
<p>To apply the migration and update the database, execute the following command:</p>
<pre><code class="lang-bash">dotnet ef database update
</code></pre>
<p>You might encounter an error like this:</p>
<pre><code class="lang-bash">  at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.&lt;&gt;c__DisplayClass0_0.&lt;.ctor&gt;b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Only the invariant culture is supported <span class="hljs-keyword">in</span> globalization-invariant mode. See https://aka.ms/GlobalizationInvariantMode <span class="hljs-keyword">for</span> more information. (Parameter <span class="hljs-string">'name'</span>)
en-us is an invalid culture identifier.
</code></pre>
<p>This error indicates that the <code>en-us</code> culture is not supported in globalization-invariant mode. To resolve this, open the <code>TodoAPI.csproj</code> file and change <code>&lt;InvariantGlobalization&gt;true&lt;/InvariantGlobalization&gt;</code> to <code>&lt;InvariantGlobalization&gt;false&lt;/InvariantGlobalization&gt;</code>.</p>
<p>After making this change, run the <code>dotnet ef database update</code> command again. If the migration is successful, you'll see an output similar to the following:</p>
<pre><code class="lang-bash">
Build started...
Build succeeded.
Applying migration <span class="hljs-string">'20240518180222_InitialCreate'</span>.
Done.
</code></pre>
<p>This indicates that the migration has been applied successfully, and the database has been updated with the necessary schema changes.</p>
<p>Congratulations! You've successfully created a migration and updated the database schema. Now, let's test our API by creating a new Todo item using Postman.</p>
<h2 id="step-14">  Step 14: Verify Your API with Postman  </h2>

<p>Before we can interact with our API, we need to ensure that our application is up and running. Start the application by executing the following command in the terminal:</p>
<pre><code class="lang-bash">dotnet run
</code></pre>
<p>With the application running, we can now use Postman to send requests to our API. Let's create a new Todo item:</p>
<ol>
<li>Open Postman and create a new request.</li>
<li>Set the request method to <code>POST</code>.</li>
<li>Enter the following URL: <code>https://localhost:5086/api/todo</code>.</li>
<li>In the <code>Headers</code> tab, set the <code>Content-Type</code> to <code>application/json</code>.</li>
<li>In the <code>Body</code> tab, select <code>raw</code> and enter the following JSON object:</li>
</ol>
<pre><code class="lang-json">{
    <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Learn ASP.NET Core"</span>,
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">"Learn how to build web applications with ASP.NET Core"</span>,
    <span class="hljs-attr">"dueDate"</span>: <span class="hljs-string">"2022-12-31T00:00:00"</span>,
    <span class="hljs-attr">"priority"</span>: <span class="hljs-number">5</span>
}
</code></pre>
<ol start="6">
<li>Click on the <code>Send</code> button to execute the request.</li>
</ol>
<p>If the request is successful, you'll receive a response similar to the one below:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"message"</span>: <span class="hljs-string">"Todo item successfully created"</span>
}
</code></pre>
<p>The image below illustrates the successful creation of a new Todo item using Postman:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/PostmanSuccess.png" alt="PostmanSuccess" width="600" height="400" loading="lazy"></p>
<p>Now that we've successfully created a new Todo item, let's retrieve all Todo items from the database using our API.</p>
<h2 id="step-15">   Step 15: Retrieve All Todo Items  </h2>

<p>To retrieve all Todo items from the database, follow these steps:</p>
<ol>
<li><p>Open Postman and create a new request.</p>
</li>
<li><p>Set the request method to <code>GET</code>. </p>
</li>
<li><p>Enter the following URL: <code>https://localhost:5086/api/todo</code>.</p>
</li>
<li><p>Click on the <code>Send</code> button to execute the request.</p>
</li>
</ol>
<p>If the request is successful, you'll receive a response similar to the one below:</p>
<pre><code class="lang-json">
   {
    <span class="hljs-attr">"message"</span>: <span class="hljs-string">"Successfully retrieved all blog posts"</span>,
    <span class="hljs-attr">"data"</span>: [
        {
            <span class="hljs-attr">"id"</span>: <span class="hljs-string">"e9898d1b-9ad3-4482-ad65-08dc77664fab"</span>,
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"string"</span>,
            <span class="hljs-attr">"description"</span>: <span class="hljs-string">"string"</span>,
            <span class="hljs-attr">"isComplete"</span>: <span class="hljs-literal">false</span>,
            <span class="hljs-attr">"dueDate"</span>: <span class="hljs-string">"2024-05-18T16:52:22.054Z"</span>,
            <span class="hljs-attr">"priority"</span>: <span class="hljs-number">5</span>,
            <span class="hljs-attr">"createdAt"</span>: <span class="hljs-string">"2024-05-18T18:14:08.1755565+00:00"</span>,
            <span class="hljs-attr">"updatedAt"</span>: <span class="hljs-string">"0001-01-01T00:00:00"</span>
        }
    ]
}
</code></pre>
<p>The image below illustrates the successful retrieval of all Todo items using Postman:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/PostmanGetAll.png" alt="PostmanGetAll" width="600" height="400" loading="lazy"></p>
<p>Congratulations! You've successfully created an API that can create and retrieve Todo items. This marks the completion of our Todo API project. You've learned how to set up a .NET Core project, define models, create a database context, implement a service layer, and create API endpoints. You've also learned how to use Postman to interact with your API and test its functionality.</p>
<p>Now let's move on to create the <code>GetByIdAsync</code>, <code>UpdateTodoAsync</code>, and <code>DeleteTodoAsync</code> methods in the <code>TodoServices</code> class and <code>TodoController</code> class.</p>
<h2 id="step-16">  Step 16: Implement the GetByIdAsync Method  </h2>

<p>The <code>GetByIdAsync</code> method retrieves a specific Todo item by its <code>Id</code>. We'll implement this method in both the <code>TodoServices</code> and <code>TodoController</code> classes.</p>
<h3 id="heading-the-todoservices-class">  The <code>TodoServices</code> Class  </h3>


<p>In the <code>TodoServices</code> class, add the following code to the <code>GetByIdAsync</code> method:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Services/TodoServices.cs</span>

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;Todo&gt; <span class="hljs-title">GetByIdAsync</span>(<span class="hljs-params">Guid id</span>)</span>
{
    <span class="hljs-keyword">var</span> todo = <span class="hljs-keyword">await</span> _context.Todos.FindAsync(id);
    <span class="hljs-keyword">if</span> (todo == <span class="hljs-literal">null</span>)
    {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> KeyNotFoundException(<span class="hljs-string">$"No Todo item with Id <span class="hljs-subst">{id}</span> found."</span>);
    }
    <span class="hljs-keyword">return</span> todo;
}
</code></pre>
<p>This method uses Entity Framework Core's <code>FindAsync</code> method to fetch a Todo item by its <code>Id</code>. If no Todo item is found, it throws a <code>KeyNotFoundException</code> with a descriptive error message.</p>
<h3 id="heading-the-todocontroller-class">   The <code>TodoController</code> Class  </h3>


<p>In the <code>TodoController</code> class, add the following code to the <code>GetByIdAsync</code> method:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Controllers/TodoController.cs</span>

[<span class="hljs-meta">HttpGet(<span class="hljs-meta-string">"{id:guid}"</span>)</span>]
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IActionResult&gt; <span class="hljs-title">GetByIdAsync</span>(<span class="hljs-params">Guid id</span>)</span>
{
    <span class="hljs-keyword">try</span>
    {
        <span class="hljs-keyword">var</span> todo = <span class="hljs-keyword">await</span> _todoServices.GetByIdAsync(id);
        <span class="hljs-keyword">if</span> (todo == <span class="hljs-literal">null</span>)
        {
            <span class="hljs-keyword">return</span> NotFound(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">$"No Todo item with Id <span class="hljs-subst">{id}</span> found."</span> });
        }
        <span class="hljs-keyword">return</span> Ok(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">$"Successfully retrieved Todo item with Id <span class="hljs-subst">{id}</span>."</span>, data = todo });
    }
    <span class="hljs-keyword">catch</span> (Exception ex)
    {
        <span class="hljs-keyword">return</span> StatusCode(<span class="hljs-number">500</span>, <span class="hljs-keyword">new</span> { message = <span class="hljs-string">$"An error occurred while retrieving the Todo item with Id <span class="hljs-subst">{id}</span>."</span>, error = ex.Message });
    }
}
</code></pre>
<p>This method calls the <code>GetByIdAsync</code> method from the <code>ITodoServices</code> interface to fetch a Todo item by its <code>Id</code>. If a Todo item is retrieved successfully, it returns an <code>Ok</code> response with a success message and the Todo item. If an error occurs during the retrieval process, it returns a <code>500 Internal Server Error</code> response with an error message.</p>
<h2 id="step-17">  Step 17: Implement the UpdateTodoAsync Method   </h2>

<p>The <code>UpdateTodoAsync</code> method in the <code>TodoServices</code> class modifies an existing Todo item in the database. Let's implement this method now.</p>
<p>Navigate to the <code>TodoServices</code> class and add the following code to the <code>UpdateTodoAsync</code> method:</p>
<pre><code class="lang-csharp">

<span class="hljs-comment">// Services/TodoServices.cs</span>

<span class="hljs-comment">// ...</span>

 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">UpdateTodoAsync</span>(<span class="hljs-params">Guid id, UpdateTodoRequest request</span>)</span>
 {
     <span class="hljs-keyword">try</span>
     {
         <span class="hljs-keyword">var</span> todo = <span class="hljs-keyword">await</span> _context.Todos.FindAsync(id);
         <span class="hljs-keyword">if</span> (todo == <span class="hljs-literal">null</span>)
         {
             <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Exception(<span class="hljs-string">$"Todo item with id <span class="hljs-subst">{id}</span> not found."</span>);
         }

         <span class="hljs-keyword">if</span> (request.Title != <span class="hljs-literal">null</span>)
         {
             todo.Title = request.Title;
         }

         <span class="hljs-keyword">if</span> (request.Description != <span class="hljs-literal">null</span>)
         {
             todo.Description = request.Description;
         }

         <span class="hljs-keyword">if</span> (request.IsComplete != <span class="hljs-literal">null</span>)
         {
             todo.IsComplete = request.IsComplete.Value;
         }

         <span class="hljs-keyword">if</span> (request.DueDate != <span class="hljs-literal">null</span>)
         {
             todo.DueDate = request.DueDate.Value;
         }

         <span class="hljs-keyword">if</span> (request.Priority != <span class="hljs-literal">null</span>)
         {
             todo.Priority = request.Priority.Value;
         }

         todo.UpdatedAt = DateTime.Now;

         <span class="hljs-keyword">await</span> _context.SaveChangesAsync();
     }
     <span class="hljs-keyword">catch</span> (Exception ex)
     {
         _logger.LogError(ex, <span class="hljs-string">$"An error occurred while updating the todo item with id <span class="hljs-subst">{id}</span>."</span>);
         <span class="hljs-keyword">throw</span>;
     }
 }

<span class="hljs-comment">// ...</span>
</code></pre>
<p>Here's a breakdown of the <code>UpdateTodoAsync</code> method:</p>
<ul>
<li><p><strong>Retrieving a Specific Todo Item</strong>: We use Entity Framework Core's <code>FindAsync</code> method to fetch a Todo item by its <code>Id</code>.</p>
</li>
<li><p><strong>Updating the Todo Item</strong>: We update the Todo item properties based on the values provided in the <code>UpdateTodoRequest</code> object.</p>
</li>
<li><p><strong>Error Handling</strong>: If no Todo item is found with the specified <code>Id</code>, we throw an exception with a descriptive error message.</p>
</li>
</ul>
<p>Now let's implement the <code>UpdateTodoAsync</code> method in the <code>TodoController</code> class. This method will modify an existing Todo item in the database.</p>
<p>Navigate to the <code>TodoController</code> class and add the following code to the <code>UpdateTodoAsync</code> method:</p>
<pre><code class="lang-csharp">
<span class="hljs-comment">// Controllers/TodoController.cs</span>

<span class="hljs-comment">// ... </span>
   [<span class="hljs-meta">HttpPut(<span class="hljs-meta-string">"{id:guid}"</span>)</span>]

   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IActionResult&gt; <span class="hljs-title">UpdateTodoAsync</span>(<span class="hljs-params">Guid id, UpdateTodoRequest request</span>)</span>
   {

       <span class="hljs-keyword">if</span> (!ModelState.IsValid)
       {
           <span class="hljs-keyword">return</span> BadRequest(ModelState);
       }

       <span class="hljs-keyword">try</span>
       {

           <span class="hljs-keyword">var</span> todo = <span class="hljs-keyword">await</span> _todoServices.GetByIdAsync(id);
           <span class="hljs-keyword">if</span> (todo == <span class="hljs-literal">null</span>)
           {
               <span class="hljs-keyword">return</span> NotFound(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">$"Todo Item  with id <span class="hljs-subst">{id}</span> not found"</span> });
           }

           <span class="hljs-keyword">await</span> _todoServices.UpdateTodoAsync(id, request);
           <span class="hljs-keyword">return</span> Ok(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">$" Todo Item  with id <span class="hljs-subst">{id}</span> successfully updated"</span> });

       }
       <span class="hljs-keyword">catch</span> (Exception ex)
       {
           <span class="hljs-keyword">return</span> StatusCode(<span class="hljs-number">500</span>, <span class="hljs-keyword">new</span> { message = <span class="hljs-string">$"An error occurred while updating blog post with id <span class="hljs-subst">{id}</span>"</span>, error = ex.Message });


       }


   }

<span class="hljs-comment">// ...</span>
</code></pre>
<p>Here's a breakdown of the <code>UpdateTodoAsync</code> method:</p>
<ul>
<li><p><strong>Model Validation</strong>: We check if the request model is valid using <code>ModelState.IsValid</code>. If the model is not valid, we return a <code>BadRequest</code> response with the model state errors.</p>
</li>
<li><p><strong>Retrieving a Specific Todo Item</strong>: We call the <code>GetByIdAsync</code> method from the <code>ITodoServices</code> interface to fetch a Todo item by its <code>Id</code>.</p>
</li>
<li><p><strong>Updating the Todo Item</strong>: If the Todo item is found, we call the <code>UpdateTodoAsync</code> method from the <code>ITodoServices</code> interface to update the Todo item.</p>
</li>
<li><p><strong>Success Response</strong>: If the Todo item is updated successfully, we return an <code>Ok</code> response with a success message.</p>
</li>
<li><p><strong>Error Handling</strong>: If an error occurs during the update process, we return a <code>500 Internal Server Error</code> response with an error message.</p>
</li>
</ul>
<h2 id="step-18"> Step 18: Implement the DeleteTodoAsync Method   </h2>

<p>The <code>DeleteTodoAsync</code> method in the <code>TodoServices</code> class removes a Todo item from the database. Let's implement this method now.</p>
<p>Navigate to the <code>TodoServices</code> class and add the following code to the <code>DeleteTodoAsync</code> method:</p>
<pre><code class="lang-csharp">

<span class="hljs-comment">// Services/TodoServices.cs</span>

<span class="hljs-comment">// ...</span>


 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">DeleteTodoAsync</span>(<span class="hljs-params">Guid id</span>)</span>
 {

     <span class="hljs-keyword">var</span> todo = <span class="hljs-keyword">await</span> _context.Todos.FindAsync(id);
     <span class="hljs-keyword">if</span>(todo != <span class="hljs-literal">null</span>)
     {
          _context.Todos.Remove(todo);
         <span class="hljs-keyword">await</span> _context.SaveChangesAsync();

     }
     <span class="hljs-keyword">else</span>
     {
         <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Exception(<span class="hljs-string">$"No  item found with the id <span class="hljs-subst">{id}</span>"</span>);
     }


 }

<span class="hljs-comment">// ...</span>
</code></pre>
<p>Here's a breakdown of the <code>DeleteTodoAsync</code> method:</p>
<ul>
<li><p><strong>Retrieving a Specific Todo Item</strong>: We use Entity Framework Core's <code>FindAsync</code> method to fetch a Todo item by its <code>Id</code>.</p>
</li>
<li><p><strong>Removing the Todo Item</strong>: If the Todo item is found, we remove it from the <code>Todos</code> DbSet in our context and save the changes asynchronously.</p>
</li>
<li><p><strong>Error Handling</strong>: If no Todo item is found with the specified <code>Id</code>, we throw an exception with a descriptive error message.</p>
</li>
</ul>
<p>Now let's implement the <code>DeleteTodoAsync</code> method in the <code>TodoController</code> class. This method will remove a Todo item from the database.</p>
<p>Navigate to the <code>TodoController</code> class and add the following code to the <code>DeleteTodoAsync</code> method:</p>
<pre><code class="lang-csharp">
<span class="hljs-comment">// Controllers/TodoController.cs</span>

<span class="hljs-comment">// ...</span>

 [<span class="hljs-meta">HttpDelete(<span class="hljs-meta-string">"{id:guid}"</span>)</span>]
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IActionResult&gt; <span class="hljs-title">DeleteTodoAsync</span>(<span class="hljs-params">Guid id</span>)</span>
 {
     <span class="hljs-keyword">try</span>
     {
         <span class="hljs-keyword">await</span> _todoServices.DeleteTodoAsync(id);
         <span class="hljs-keyword">return</span> Ok(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">$"Todo  with id <span class="hljs-subst">{id}</span> successfully deleted"</span> });

     }
     <span class="hljs-keyword">catch</span> (Exception ex)
     {
         <span class="hljs-keyword">return</span> StatusCode(<span class="hljs-number">500</span>, <span class="hljs-keyword">new</span> { message = <span class="hljs-string">$"An error occurred while deleting Todo Item  with id <span class="hljs-subst">{id}</span>"</span>, error = ex.Message });

     }
 }



<span class="hljs-comment">// ...</span>
</code></pre>
<p>Here's a breakdown of the <code>DeleteTodoAsync</code> method:</p>
<ul>
<li><p><strong>Removing the Todo Item</strong>: We call the <code>DeleteTodoAsync</code> method from the <code>ITodoServices</code> interface to remove a Todo item by its <code>Id</code>.</p>
</li>
<li><p><strong>Success Response</strong>: If the Todo item is deleted successfully, we return an <code>Ok</code> response with a success message.</p>
</li>
<li><p><strong>Error Handling</strong>: If an error occurs during the deletion process, we return a <code>500 Internal Server Error</code> response with an error message.</p>
</li>
</ul>
<p>Now your <code>TodoServices</code> class should look like this:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Services/TodoServices.cs</span>

<span class="hljs-keyword">using</span> AutoMapper;
<span class="hljs-keyword">using</span> Microsoft.EntityFrameworkCore;
<span class="hljs-keyword">using</span> TodoAPI.AppDataContext;
<span class="hljs-keyword">using</span> TodoAPI.Contracts;
<span class="hljs-keyword">using</span> TodoAPI.Interface;
<span class="hljs-keyword">using</span> TodoAPI.Models;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">TodoAPI.Services</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TodoServices</span> : <span class="hljs-title">ITodoServices</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> TodoDbContext _context;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> ILogger&lt;TodoServices&gt; _logger;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IMapper _mapper;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">TodoServices</span>(<span class="hljs-params">TodoDbContext context, ILogger&lt;TodoServices&gt; logger, IMapper mapper</span>)</span>
        {
            _context = context;
            _logger = logger;
            _mapper = mapper;
        }




        <span class="hljs-comment">//  Create Todo for it to be saved in the datbase </span>

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">CreateTodoAsync</span>(<span class="hljs-params">CreateTodoRequest request</span>)</span>
        {
            <span class="hljs-keyword">try</span>
            {
                <span class="hljs-keyword">var</span> todo = _mapper.Map&lt;Todo&gt;(request);
                todo.CreatedAt = DateTime.Now;
                _context.Todos.Add(todo);
                <span class="hljs-keyword">await</span> _context.SaveChangesAsync();
            }
            <span class="hljs-keyword">catch</span> (Exception ex)
            {
                _logger.LogError(ex, <span class="hljs-string">"An error occurred while creating the todo item."</span>);
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Exception(<span class="hljs-string">"An error occurred while creating the todo item."</span>);
            }
        }


        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;Todo&gt; <span class="hljs-title">GetByIdAsync</span>(<span class="hljs-params">Guid id</span>)</span>
        {
            <span class="hljs-keyword">var</span> todo = <span class="hljs-keyword">await</span> _context.Todos.FindAsync(id);
            <span class="hljs-keyword">if</span> (todo == <span class="hljs-literal">null</span>)
            {
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Exception(<span class="hljs-string">$" No Items with <span class="hljs-subst">{id}</span> found "</span>);
            }
            <span class="hljs-keyword">return</span> todo;
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">UpdateTodoAsync</span>(<span class="hljs-params">Guid id, UpdateTodoRequest request</span>)</span>
        {
            <span class="hljs-keyword">try</span>
            {
                <span class="hljs-keyword">var</span> todo = <span class="hljs-keyword">await</span> _context.Todos.FindAsync(id);
                <span class="hljs-keyword">if</span> (todo == <span class="hljs-literal">null</span>)
                {
                    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Exception(<span class="hljs-string">$"Todo item with id <span class="hljs-subst">{id}</span> not found."</span>);
                }

                <span class="hljs-keyword">if</span> (request.Title != <span class="hljs-literal">null</span>)
                {
                    todo.Title = request.Title;
                }

                <span class="hljs-keyword">if</span> (request.Description != <span class="hljs-literal">null</span>)
                {
                    todo.Description = request.Description;
                }

                <span class="hljs-keyword">if</span> (request.IsComplete != <span class="hljs-literal">null</span>)
                {
                    todo.IsComplete = request.IsComplete.Value;
                }

                <span class="hljs-keyword">if</span> (request.DueDate != <span class="hljs-literal">null</span>)
                {
                    todo.DueDate = request.DueDate.Value;
                }

                <span class="hljs-keyword">if</span> (request.Priority != <span class="hljs-literal">null</span>)
                {
                    todo.Priority = request.Priority.Value;
                }

                todo.UpdatedAt = DateTime.Now;

                <span class="hljs-keyword">await</span> _context.SaveChangesAsync();
            }
            <span class="hljs-keyword">catch</span> (Exception ex)
            {
                _logger.LogError(ex, <span class="hljs-string">$"An error occurred while updating the todo item with id <span class="hljs-subst">{id}</span>."</span>);
                <span class="hljs-keyword">throw</span>;
            }
        }
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IEnumerable&lt;Todo&gt;&gt; GetAllAsync()
        {
            <span class="hljs-keyword">var</span> todo = <span class="hljs-keyword">await</span> _context.Todos.ToListAsync();
            <span class="hljs-keyword">if</span> (todo == <span class="hljs-literal">null</span>)
            {
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Exception(<span class="hljs-string">" No Todo items found"</span>);
            }
            <span class="hljs-keyword">return</span> todo;

        }
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">DeleteTodoAsync</span>(<span class="hljs-params">Guid id</span>)</span>
        {

            <span class="hljs-keyword">var</span> todo = <span class="hljs-keyword">await</span> _context.Todos.FindAsync(id);
            <span class="hljs-keyword">if</span> (todo != <span class="hljs-literal">null</span>)
            {
                _context.Todos.Remove(todo);
                <span class="hljs-keyword">await</span> _context.SaveChangesAsync();

            }
            <span class="hljs-keyword">else</span>
            {
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Exception(<span class="hljs-string">$"No  item found with the id <span class="hljs-subst">{id}</span>"</span>);
            }


        }




    }
}
</code></pre>
<p>Now your <code>TodoController</code> class should look like this:</p>
<pre><code class="lang-csharp">
<span class="hljs-keyword">using</span> Microsoft.AspNetCore.Mvc;
<span class="hljs-keyword">using</span> TodoAPI.Contracts;
<span class="hljs-keyword">using</span> TodoAPI.Interface;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">TodoAPI.Controllers</span>
{
    [<span class="hljs-meta">ApiController</span>]
    [<span class="hljs-meta">Route(<span class="hljs-meta-string">"api/[controller]"</span>)</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TodoController</span> : <span class="hljs-title">ControllerBase</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> ITodoServices _todoServices;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">TodoController</span>(<span class="hljs-params">ITodoServices todoServices</span>)</span>
        {
            _todoServices = todoServices;
        }



        <span class="hljs-comment">// Creating new Todo Item</span>
        [<span class="hljs-meta">HttpPost</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IActionResult&gt; <span class="hljs-title">CreateTodoAsync</span>(<span class="hljs-params">CreateTodoRequest request</span>)</span>
        {
            <span class="hljs-keyword">if</span> (!ModelState.IsValid)
            {
                <span class="hljs-keyword">return</span> BadRequest(ModelState);
            }


            <span class="hljs-keyword">try</span>
            {

                <span class="hljs-keyword">await</span> _todoServices.CreateTodoAsync(request);
                <span class="hljs-keyword">return</span> Ok(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">"Blog post successfully created"</span> });

            }
            <span class="hljs-keyword">catch</span> (Exception ex)
            {
                <span class="hljs-keyword">return</span> StatusCode(<span class="hljs-number">500</span>, <span class="hljs-keyword">new</span> { message = <span class="hljs-string">"An error occurred while creating the  crating Todo Item"</span>, error = ex.Message });

            }
        }

        <span class="hljs-comment">// Get all Todo Items</span>

        [<span class="hljs-meta">HttpGet</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IActionResult&gt; <span class="hljs-title">GetAllAsync</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-keyword">try</span>
            {
                <span class="hljs-keyword">var</span> todo = <span class="hljs-keyword">await</span> _todoServices.GetAllAsync();
                <span class="hljs-keyword">if</span> (todo == <span class="hljs-literal">null</span> || !todo.Any())
                {
                    <span class="hljs-keyword">return</span> Ok(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">"No Todo Items  found"</span> });
                }
                <span class="hljs-keyword">return</span> Ok(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">"Successfully retrieved all blog posts"</span>, data = todo });

            }
            <span class="hljs-keyword">catch</span> (Exception ex)
            {
                <span class="hljs-keyword">return</span> StatusCode(<span class="hljs-number">500</span>, <span class="hljs-keyword">new</span> { message = <span class="hljs-string">"An error occurred while retrieving all Tood it posts"</span>, error = ex.Message });


            }
        }

        [<span class="hljs-meta">HttpGet(<span class="hljs-meta-string">"{id:guid}"</span>)</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IActionResult&gt; <span class="hljs-title">GetByIdAsync</span>(<span class="hljs-params">Guid id</span>)</span>
        {
            <span class="hljs-keyword">try</span>
            {

                <span class="hljs-keyword">var</span> todo = <span class="hljs-keyword">await</span> _todoServices.GetByIdAsync(id);
                <span class="hljs-keyword">if</span> (todo == <span class="hljs-literal">null</span>)
                {
                    <span class="hljs-keyword">return</span> NotFound(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">$"Now Todo item with id <span class="hljs-subst">{id}</span> not found"</span> });

                }
                <span class="hljs-keyword">return</span> Ok(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">$"Successfully retrieved  todo item with id <span class="hljs-subst">{id}</span>"</span>, data = todo });

            }
            <span class="hljs-keyword">catch</span> (Exception ex)
            {
                <span class="hljs-keyword">return</span> StatusCode(<span class="hljs-number">500</span>, <span class="hljs-keyword">new</span> { message = <span class="hljs-string">$"An error occurred while retrieving   todo item  with id <span class="hljs-subst">{id}</span>"</span>, error = ex.Message });

            }
        }



        [<span class="hljs-meta">HttpPut(<span class="hljs-meta-string">"{id:guid}"</span>)</span>]

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IActionResult&gt; <span class="hljs-title">UpdateTodoAsync</span>(<span class="hljs-params">Guid id, UpdateTodoRequest request</span>)</span>
        {

            <span class="hljs-keyword">if</span> (!ModelState.IsValid)
            {
                <span class="hljs-keyword">return</span> BadRequest(ModelState);
            }

            <span class="hljs-keyword">try</span>
            {

                <span class="hljs-keyword">var</span> todo = <span class="hljs-keyword">await</span> _todoServices.GetByIdAsync(id);
                <span class="hljs-keyword">if</span> (todo == <span class="hljs-literal">null</span>)
                {
                    <span class="hljs-keyword">return</span> NotFound(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">$"Todo Item  with id <span class="hljs-subst">{id}</span> not found"</span> });
                }

                <span class="hljs-keyword">await</span> _todoServices.UpdateTodoAsync(id, request);
                <span class="hljs-keyword">return</span> Ok(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">$" Todo Item  with id <span class="hljs-subst">{id}</span> successfully updated"</span> });

            }
            <span class="hljs-keyword">catch</span> (Exception ex)
            {
                <span class="hljs-keyword">return</span> StatusCode(<span class="hljs-number">500</span>, <span class="hljs-keyword">new</span> { message = <span class="hljs-string">$"An error occurred while updating blog post with id <span class="hljs-subst">{id}</span>"</span>, error = ex.Message });


            }


        }


        [<span class="hljs-meta">HttpDelete(<span class="hljs-meta-string">"{id:guid}"</span>)</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IActionResult&gt; <span class="hljs-title">DeleteTodoAsync</span>(<span class="hljs-params">Guid id</span>)</span>
        {
            <span class="hljs-keyword">try</span>
            {
                <span class="hljs-keyword">await</span> _todoServices.DeleteTodoAsync(id);
                <span class="hljs-keyword">return</span> Ok(<span class="hljs-keyword">new</span> { message = <span class="hljs-string">$"Todo  with id <span class="hljs-subst">{id}</span> successfully deleted"</span> });

            }
            <span class="hljs-keyword">catch</span> (Exception ex)
            {
                <span class="hljs-keyword">return</span> StatusCode(<span class="hljs-number">500</span>, <span class="hljs-keyword">new</span> { message = <span class="hljs-string">$"An error occurred while deleting Todo Item  with id <span class="hljs-subst">{id}</span>"</span>, error = ex.Message });

            }
        }


    }
}
</code></pre>
<p>Now that we've implemented the <code>GetByIdAsync</code>, <code>UpdateTodoAsync</code>, and <code>DeleteTodoAsync</code> methods in the <code>TodoServices</code> and <code>TodoController</code> classes, we can test our API to ensure that everything is working as expected.</p>
<h2 id="step-19"> Step 19: Test Your API Endpoints with Postman   </h2>

<p>With our application up and running, we can now test all our API endpoints. We'll create new Todo items, retrieve all Todo items, fetch a specific Todo item by its <code>Id</code>, update a Todo item, and delete a Todo item using Postman. Let's start by creating three new Todo items.</p>
<p>Note that we'll be creating these Todo items one at a time, not all at once. Follow these steps for each Todo item:</p>
<ol>
<li>Open Postman and create a new request.</li>
<li>Set the request method to <code>POST</code>.</li>
<li>Enter the following URL: <code>http://localhost:5086/api/todo</code>.</li>
<li>In the <code>Headers</code> tab, set the <code>Content-Type</code> to <code>application/json</code>.</li>
<li>In the <code>Body</code> tab, select <code>raw</code> and enter one of the following JSON objects:</li>
</ol>
<p>For the first Todo item:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Learn ASP.NET Core"</span>,
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">"Learn how to build web applications with ASP.NET Core"</span>,
    <span class="hljs-attr">"dueDate"</span>: <span class="hljs-string">"2022-12-31T00:00:00"</span>,
    <span class="hljs-attr">"priority"</span>: <span class="hljs-number">2</span>
}
</code></pre>
<p>For the second Todo item:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Learn C#"</span>,
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">"Learn how to build web applications with C#"</span>,
    <span class="hljs-attr">"dueDate"</span>: <span class="hljs-string">"2022-12-31T00:00:00"</span>,
    <span class="hljs-attr">"priority"</span>: <span class="hljs-number">3</span>
}
</code></pre>
<p>For the third Todo item:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Learn SQL"</span>,
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">"Learn how to build web applications with SQL"</span>,
    <span class="hljs-attr">"dueDate"</span>: <span class="hljs-string">"2022-12-31T00:00:00"</span>,
    <span class="hljs-attr">"priority"</span>: <span class="hljs-number">1</span>
}
</code></pre>
<ol start="6">
<li>Click on the <code>Send</code> button to execute the request for each Todo item.</li>
</ol>
<p>If each request is successful, you'll receive a response similar to the one below:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"message"</span>: <span class="hljs-string">"Todo item successfully created"</span>
}
</code></pre>
<p>This indicates that the Todo item has been successfully created. Repeat the steps for each Todo item.</p>
<h3 id="heading-how-to-retrieve-all-todo-items"> How to Retrieve All Todo Items   </h3>

<p>To fetch all Todo items from the database, follow these steps:</p>
<ol>
<li>Launch Postman and initiate a new request.</li>
<li>Set the HTTP method to <code>GET</code>.</li>
<li>Input the following URL: <code>http://localhost:5086/api/todo</code>.</li>
<li>Click the <code>Send</code> button to execute the request.</li>
</ol>
<p>The image below demonstrates a successful retrieval of all Todo items using Postman:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/PostmanGetAll-1.png" alt="PostmanGetAll-1" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-fetch-a-specific-todo-item-by-id">  How to Fetch a Specific Todo Item by Id  </h3>

<p>To retrieve a specific Todo item using its <code>Id</code>, follow these steps:</p>
<ol>
<li>Launch Postman and initiate a new request.</li>
<li>Set the HTTP method to <code>GET</code>.</li>
<li>Input the following URL: <code>http://localhost:5086/api/todo/{id}</code>, replacing <code>{id}</code> with the <code>Id</code> of the Todo item you wish to retrieve. For example, <code>http://localhost:5086/api/todo/e9898d1b-9ad3-4482-ad65-08dc77664fab</code>.</li>
<li>Click the <code>Send</code> button to execute the request.</li>
</ol>
<p>Upon successful execution, you'll receive a response similar to the one below:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"message"</span>: <span class="hljs-string">"Successfully retrieved  todo item with id e9898d1b-9ad3-4482-ad65-08dc77664fab"</span>,
    <span class="hljs-attr">"data"</span>: {
        <span class="hljs-attr">"id"</span>: <span class="hljs-string">"e9898d1b-9ad3-4482-ad65-08dc77664fab"</span>,
        <span class="hljs-attr">"title"</span>: <span class="hljs-string">"string"</span>,
        <span class="hljs-attr">"description"</span>: <span class="hljs-string">"string"</span>,
        <span class="hljs-attr">"isComplete"</span>: <span class="hljs-literal">false</span>,
        <span class="hljs-attr">"dueDate"</span>: <span class="hljs-string">"2024-05-18T16:52:22.054"</span>,
        <span class="hljs-attr">"priority"</span>: <span class="hljs-number">5</span>,
        <span class="hljs-attr">"createdAt"</span>: <span class="hljs-string">"2024-05-18T18:14:08.1755565"</span>,
        <span class="hljs-attr">"updatedAt"</span>: <span class="hljs-string">"0001-01-01T00:00:00"</span>
    }
}
</code></pre>
<p>The image below demonstrates the successful retrieval of a specific Todo item using Postman:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/PostmanGetById.png" alt="PostmanGetById" width="600" height="400" loading="lazy">)</p>
<h3 id="heading-how-to-update-a-todo-item">   How to Update a Todo Item </h3>


<p>In our Todo model, we have a property <code>isComplete</code> which is initially set to <code>false</code> when a Todo item is created. This property is used to indicate whether a task has been completed or not. To mark a task as complete, we need to update this property to <code>true</code>. Note that we can only update one Todo item at a time, and we identify the item to update by its <code>Id</code>.</p>
<p>Let's fetch all the Todo items, select one and update it by setting the <code>isComplete</code> property to <code>true</code>.</p>
<p>Follow these steps to update a Todo item:</p>
<ol>
<li>Launch Postman and initiate a new request.</li>
<li>Set the HTTP method to <code>PUT</code>.</li>
<li>Input the following URL: <code>http://localhost:5086/api/todo/{id}</code>, replacing <code>{id}</code> with the <code>Id</code> of the Todo item you wish to update. For example, <code>http://localhost:5086/api/todo/e9898d1b-9ad3-4482-ad65-08dc77664fab</code>.</li>
<li>In the <code>Headers</code> tab, set the <code>Content-Type</code> to <code>application/json</code>.</li>
<li>In the <code>Body</code> tab, select <code>raw</code> and enter the following JSON object:</li>
</ol>
<pre><code class="lang-json">{
    <span class="hljs-attr">"id"</span>: <span class="hljs-string">"21ebe2c2-79c0-45d4-4139-08dc789e3eb2"</span>,
    <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Learn C#"</span>,
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">"Learn how to build web applications with C#"</span>,
    <span class="hljs-attr">"isComplete"</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">// Set the isComplete to true</span>
    <span class="hljs-attr">"dueDate"</span>: <span class="hljs-string">"2022-12-31T00:00:00"</span>,
    <span class="hljs-attr">"priority"</span>: <span class="hljs-number">3</span>,
    <span class="hljs-attr">"createdAt"</span>: <span class="hljs-string">"2024-05-20T07:27:39.3730049+00:00"</span>,
    <span class="hljs-attr">"updatedAt"</span>: <span class="hljs-string">"0001-01-01T00:00:00"</span>
}
</code></pre>
<ol start="6">
<li>Click the <code>Send</code> button to execute the request.</li>
</ol>
<p>Upon successful execution, you'll receive a response similar to the one below:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"message"</span>: <span class="hljs-string">"Todo Item with id 21ebe2c2-79c0-45d4-4139-08dc789e3eb2 successfully updated"</span>
}
</code></pre>
<p>The image below demonstrates the successful update of a Todo item using Postman:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/PostmanUpdate.png" alt="PostmanUpdate" width="600" height="400" loading="lazy"></p>
<p><strong>Note</strong>: The <code>isComplete</code> property of the Todo item has been updated to <code>true</code>. Now, when you fetch all Todo items from the database, you will see the <code>isComplete</code> property is <code>true</code> for the updated Todo item.</p>
<p>Now let's see how to delete a Todo item from the database.</p>
<h3 id="heading-how-to-delete-a-todo-item">  How to Delete a Todo Item </h3>


<p>To remove a Todo item from the database, follow these steps: </p>
<ol>
<li>Open Postman and create a new request.</li>
<li>Set the HTTP method to <code>DELETE</code>.</li>
<li>Enter the following URL: <code>http://localhost:5086/api/todo/{id}</code>, replacing <code>{id}</code> with the <code>Id</code> of the Todo item you intend to remove. For instance, <code>http://localhost:5086/api/todo/e9898d1b-9ad3-4482-ad65-08dc77664fab</code>.</li>
<li>Click the <code>Send</code> button to execute the request.</li>
</ol>
<p>If the request is successful, you'll receive a response similar to the one below:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"message"</span>: <span class="hljs-string">"Todo item with id 21ebe2c2-79c0-45d4-4139-08dc789e3eb2 successfully deleted"</span>
}
</code></pre>
<p>The image below illustrates the successful deletion of a Todo item using Postman:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/PostmanDelete.png" alt="PostmanDelete" width="600" height="400" loading="lazy"></p>
<p>Well done! You've successfully implemented the <code>GetByIdAsync</code>, <code>UpdateTodoAsync</code>, and <code>DeleteTodoAsync</code> methods in the <code>TodoServices</code> and <code>TodoController</code> classes. You've also verified your API endpoints using Postman to ensure they're functioning as expected. You can </p>
<h3 id="heading-source-code">   Source Code  </h3>


<p>The entire source code for this project is readily available in the <a target="_blank" href="https://github.com/Clifftech123/TodoAPI">TodoAPI</a> GitHub repository. I encourage you to delve into the codebase, tinker with various functionalities, and bolster your proficiency in crafting APIs using ASP.NET Core 8.</p>
<h2 id="conclusion"> Conclusion  </h2>

<p>In this guide, we've journeyed through the process of constructing a robust Todo API using the power of ASP.NET Core 8. We initiated our project from scratch, meticulously defining the essential models that form the backbone of our Todo application.</p>
<p>We then created a database context, a crucial step that facilitated our interaction with the database. To further streamline this interaction, we implemented a service layer, effectively abstracting the complexities of direct database operations.</p>
<p>Next, we created our API endpoints. These endpoints serve as the gateways for <code>creating</code>, <code>retrieving</code>, <code>updating</code>, and <code>deleting</code> Todo items, thereby providing comprehensive functionality to our application.</p>
<p>The final stage of our journey involved rigorous testing of our API using Postman. This ensured that our application was not only built as per our design but also functioned as expected, providing a reliable and efficient service.</p>
<p>As we conclude, it's important to remember that the knowledge gained here forms a solid foundation for building more complex and feature-rich APIs. The journey of learning and exploration doesn't end here – it's just the beginning. Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
