<?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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Benedict Odoh on Medium]]></title>
        <description><![CDATA[Stories by Benedict Odoh on Medium]]></description>
        <link>https://medium.com/@benedictodoh?source=rss-771b70f7b31d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*x1Il8oQm_piqW8m3T9hN5A.png</url>
            <title>Stories by Benedict Odoh on Medium</title>
            <link>https://medium.com/@benedictodoh?source=rss-771b70f7b31d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:50:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@benedictodoh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding Pagination in .NET APIs]]></title>
            <link>https://benedictodoh.medium.com/understanding-pagination-in-net-apis-87f4eec959ea?source=rss-771b70f7b31d------2</link>
            <guid isPermaLink="false">https://medium.com/p/87f4eec959ea</guid>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[webapi]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Benedict Odoh]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 06:03:59 GMT</pubDate>
            <atom:updated>2026-11-19T06:03:59.599Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine building an API that retrieves customers from a database. As the application grows, the Customers table may contain thousands or even millions of records.</p><p>Returning every customer in a single API response is not ideal. It increases the amount of data transferred over the network, consumes more memory, and can affect response time.</p><p><strong>Pagination solves this problem by dividing a large collection of records into smaller, manageable portions called pages.</strong></p><p>Rather than retrieving all customers at once, the API allows a client to request a specific portion of the records.</p><p>For example, instead of returning 1,000 customers in one response, the client can request 20 customers at a time.</p><p>This means the API retrieves only the records required for the requested page.</p><h3>Types of Pagination</h3><p>There are two commonly used pagination approaches: <strong>offset-based pagination</strong> and <strong>cursor-based pagination</strong>.</p><h4>Offset-Based Pagination</h4><p>Offset-based pagination retrieves records by specifying how many records to skip and how many to return.</p><p>For example, if a client requests page 2 with a page size of 10, the API skips the first 10 records and retrieves the next 10.</p><p>This approach is commonly implemented using Skip() and Take() in Entity Framework Core.</p><h4>Cursor-Based Pagination</h4><p>Cursor-based pagination uses a value from the last record retrieved to determine where the next set of records should begin.</p><p>For example, if the last customer returned has an ID of 20, the next request can retrieve customers whose IDs are greater than 20.</p><pre>var customers = await _context.Customers<br>    .Where(c =&gt; c.CustomerId &gt; lastCustomerId)<br>    .OrderBy(c =&gt; c.CustomerId)<br>    .Take(pageSize)<br>    .ToListAsync();</pre><p>Unlike offset pagination, this approach does not calculate how many records to skip. Instead, it uses a reference point (the cursor) to continue retrieving records.</p><p>Cursor-based pagination is particularly useful when working with large datasets or continuously changing data, such as activity feeds and transaction histories.</p><p>However, it does not naturally support jumping directly to an arbitrary page, such as page 15.</p><p>For most conventional APIs that display numbered pages, offset-based pagination is a straightforward starting point.</p><h3>Understanding Page Number and Page Size</h3><p>When implementing offset-based pagination, two important parameters are involved: PageNumber and PageSize.</p><p><strong>PageNumber</strong> identifies the page the client wants to retrieve, while <strong>PageSize</strong> specifies the number of records that should be returned on that page.</p><p>Consider a customer table containing 50 records, with a page size of 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*VeCDK6D2PHlvnEc3kNiUSg.png" /></figure><p>The distinction is important: page number determines <em>where to retrieve records from</em>, while page size determines <em>how many records to retrieve</em>.</p><p>To calculate how many records should be skipped, we use:</p><pre>skip = (pageNumber - 1) * pageSize;</pre><p>For example, requesting page 3 with a page size of 10 gives:</p><pre>skip = (3 - 1) * 10; // skip = 20</pre><p>Therefore, the query skips the first 20 records before retrieving the next 10.</p><h3>Applying Pagination to a Database Query via EF Core</h3><p>When using Entity Framework Core, Skip() and Take() are commonly used to implement offset-based pagination.</p><p>Consider the following query:</p><pre>var customers = await _context.Customers<br>    .OrderBy(c =&gt; c.CustomerId)<br>    .Skip((pageNumber - 1) * pageSize)<br>    .Take(pageSize)<br>    .ToListAsync();</pre><p>Here is what each method does:</p><ul><li>OrderBy() determines the order in which records are retrieved.</li><li>Skip() excludes the specified number of records.</li><li>Take() limits the number of records returned.</li><li>ToListAsync() executes the query and retrieves the results asynchronously.</li></ul><p>The ordering is particularly important. Without a consistent ordering, the database is not guaranteed to return records in the same sequence across requests.</p><p>For example, ordering by CustomerId gives the query a predictable sequence, assuming that CustomerId is unique.</p><p>Entity Framework Core translates this operation into SQL pagination syntax supported by the database provider. In SQL Server, this commonly uses ORDER BY together with OFFSET and FETCH NEXT.</p><pre>SELECT *<br>FROM Customers<br>ORDER BY CustomerId<br>OFFSET 20 ROWS<br>FETCH NEXT 10 ROWS ONLY;</pre><p>The important point is that pagination should happen in the database query rather than retrieving every record into application memory and applying pagination afterwards.</p><h3>Pagination Metadata</h3><p>Suppose an API returns 10 customers. The client receives the records, but how does it know whether there are more customers to retrieve?</p><p>How does it determine the total number of pages? How does it know whether the current page is the first or last?</p><p>This is where <strong>pagination metadata</strong> becomes important.</p><p>Pagination metadata provides additional information about the retrieved records, allowing the client application to implement navigation controls and determine whether more records are available.</p><p>Common metadata properties include:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*mdfwFCSVU_eIA4jHN6MwbQ.png" /></figure><p>For example, if a database contains 50 matching customers and the client requests 10 records per page, the total number of pages is:</p><pre>var totalPages = (int)Math.Ceiling(<br>    (double)totalRecords / pageSize);</pre><p>The metadata allows a frontend application to display page navigation, disable the Previous button on the first page, and disable the Next button on the last page.</p><h3>Creating a Paginated Response Model</h3><p>Rather than returning a list of records without any additional information, we can create a reusable model that contains both the retrieved records and their pagination metadata.</p><p>Using generics, we can make this model reusable across different entities, such as customers, products, orders, and transactions.</p><pre>public class PaginatedResponse&lt;T&gt;<br>{<br>    public List&lt;T&gt; Items { get; set; } = [];<br><br>    public int CurrentPage { get; set; }<br><br>    public int PageSize { get; set; }<br><br>    public int TotalRecords { get; set; }<br><br>    public int TotalPages { get; set; }<br><br>    public bool HasPreviousPage =&gt; CurrentPage &gt; 1;<br><br>    public bool HasNextPage =&gt; CurrentPage &lt; TotalPages;<br>}</pre><h3>Adding Pagination to a Standardized API Response</h3><p>Having previously established what a standardized API response model looks like, we can extend it to support pagination without changing the structure of our existing ApiResponse&lt;T&gt; class.</p><p>Recall our existing response model in the <a href="https://benedictodoh.medium.com/c2dbe7e6b0d9">article</a>:</p><pre>public class ApiResponse&lt;T&gt;<br>{<br>    public bool Success { get; set; }<br><br>    public int StatusCode { get; set; }<br><br>    public string Message { get; set; } = string.Empty;<br><br>    public T? Data { get; set; }<br><br>    public List&lt;ApiError&gt;? Errors { get; set; }<br>}<br><br>public class ApiError<br>{<br>    public string Field { get; set; } = string.Empty;<br><br>    public string Code { get; set; } = string.Empty;<br><br>    public string Message { get; set; } = string.Empty;<br>}</pre><p>Now we can use the pagination model as the generic type argument for our standard API response.</p><pre>ApiResponse&lt;PaginatedResponse&lt;CustomerDto&gt;&gt;</pre><h4>Sample Paginated Success Response</h4><p>Sample request:</p><pre>GET /api/customers?pageNumber=1&amp;pageSize=2</pre><p>The response might look like this:</p><pre>{<br>    &quot;success&quot;: true,<br>    &quot;statusCode&quot;: 200,<br>    &quot;message&quot;: &quot;Customers retrieved successfully&quot;,<br>    &quot;data&quot;: {<br>        &quot;items&quot;: [<br>            {<br>                &quot;id&quot;: 23,<br>                &quot;firstName&quot;: &quot;Ben&quot;,<br>                &quot;lastName&quot;: &quot;Doe&quot;,<br>                &quot;email&quot;: &quot;ben@example.com&quot;<br>            },<br>            {<br>                &quot;id&quot;: 24,<br>                &quot;firstName&quot;: &quot;Jane&quot;,<br>                &quot;lastName&quot;: &quot;Smith&quot;,<br>                &quot;email&quot;: &quot;jane@example.com&quot;<br>            }<br>        ],<br>        &quot;currentPage&quot;: 1,<br>        &quot;pageSize&quot;: 2,<br>        &quot;totalRecords&quot;: 10,<br>        &quot;totalPages&quot;: 5,<br>        &quot;hasPreviousPage&quot;: false,<br>        &quot;hasNextPage&quot;: true<br>    },<br>    &quot;errors&quot;: null<br>}</pre><h4>Sample Paginated Error Response</h4><p>The same standardized response structure can also accommodate errors.</p><p>For example, if the client supplies an invalid page number or an invalid page size, the API can return an appropriate error response:</p><p>Sample request:</p><pre>GET /api/customers?pageNumber=-1&amp;pageSize=2</pre><p>Sample Response:</p><pre>{<br>    &quot;success&quot;: false,<br>    &quot;statusCode&quot;: 400,<br>    &quot;message&quot;: &quot;Invalid pagination parameters&quot;,<br>    &quot;data&quot;: null,<br>    &quot;errors&quot;: [<br>        {<br>            &quot;field&quot;: &quot;PageNumber&quot;,<br>            &quot;code&quot;: &quot;INVALID_PAGE_NUMBER&quot;,<br>            &quot;message&quot;: &quot;Page number must be greater than zero&quot;<br>        }<br>    ]<br>}</pre><p>The Data property is null because no paginated result was returned, while Errors contains the details of the validation failure.</p><h3>What If the Query Has Filters?</h3><p>Suppose the API allows clients to retrieve customers based on their first name.</p><p>The filter must be applied before both the total count and the pagination operations.</p><pre>var query = _context.Customers<br>    .AsNoTracking()<br>    .Where(c =&gt; c.FirstName == firstName);<br><br>var totalRecords = await query.CountAsync();<br><br>var customers = await query<br>    .OrderBy(c =&gt; c.CustomerId)<br>    .Skip((pageNumber - 1) * pageSize)<br>    .Take(pageSize)<br>    .ToListAsync();</pre><p>This ensures that TotalRecords represents the number of customers matching the filter, rather than the total number of customers in the database.</p><h3>Validating Pagination Parameters</h3><p>An API should not blindly accept every pagination value supplied by a client.</p><p>For example, requesting page 0 or a negative page size does not make sense. Similarly, allowing a client to request 100,000 records in one page could undermine the benefits of pagination.</p><p>A simple validation approach would adjust invalid parameters to default values:</p><pre>if (pageNumber &lt; 1)<br>    pageNumber = 1;<br><br>if (pageSize &lt; 1)<br>    pageSize = 10;<br><br>if (pageSize &gt; 100)<br>    pageSize = 100;</pre><h3>Limitations of Offset-Based Pagination</h3><p>Although offset-based pagination is straightforward, it has some limitations.</p><p>One concern is performance when retrieving records from very large datasets. As the requested page moves further into the dataset, the database may need to process an increasingly large number of preceding rows to reach the requested offset.</p><p>Another concern is data changing between requests.</p><p>For example, a client retrieves page 1, then a new record is inserted before the records on page 2 are retrieved. Depending on the ordering, the client may encounter duplicated or skipped records when navigating between pages.</p><p>This is one reason cursor-based pagination can be a better option for large datasets or continuously changing collections.</p><p>However, offset-based pagination remains useful when users need numbered pages, direct navigation to a particular page, or a relatively simple pagination implementation.</p><h3>Conclusion</h3><p>Pagination is an important technique for building APIs that retrieve large collections of records efficiently.</p><p>Offset-based pagination uses page numbers and page sizes to determine which records to retrieve, while cursor-based pagination uses a reference point to continue retrieving records.</p><p>When implementing pagination with Entity Framework Core, Skip() and Take() allow us to retrieve the required records directly from the database. We should also apply consistent ordering, calculate the total number of matching records, return useful pagination metadata, and validate incoming pagination parameters.</p><p>Finally, a generic paginated response model allows the same pagination structure to be reused across different entities and endpoints.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87f4eec959ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Response Structure in ASP.NET Core Web APIs]]></title>
            <link>https://benedictodoh.medium.com/api-response-structure-in-asp-net-core-web-apis-c2dbe7e6b0d9?source=rss-771b70f7b31d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2dbe7e6b0d9</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Benedict Odoh]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 18:01:04 GMT</pubDate>
            <atom:updated>2026-11-24T19:17:25.683Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous article, we explored <strong>Generics in C#</strong> and learned how they allow us to build reusable, type-safe components that work with different data types. One practical place where generics shine in real-world ASP.NET Core applications is in the design of <strong>API response models</strong>.</p><p>When building Web APIs, returning data is only part of the job. A well-designed API must also communicate whether a request succeeded, provide useful messages, supply error details when something goes wrong, and do all of this consistently across every endpoint. This is where a standardized API response structure becomes valuable.</p><p>In this article, we’ll gradually build an understanding of API response structures, examine their common components, and then implement a reusable generic ApiResponse&lt;T&gt; model in ASP.NET Core.</p><h3>Understanding API Response Structure</h3><p>An API response structure refers to the format used by an API when sending data back to a client.</p><p>Whenever a frontend application, mobile app, or another service calls an endpoint, the API provides a response, typically in JSON format. The structure of that JSON is the API response structure.</p><p>Consider these endpoints:</p><p>Customer Endpoint:</p><pre>GET /api/customers/1</pre><p>Response:</p><pre>{<br>  &quot;id&quot;: 1,<br>  &quot;name&quot;: &quot;John Doe&quot;<br>}</pre><p>Product Endpoint:</p><pre>GET /api/products/5</pre><p>Response:</p><pre>{<br>  &quot;success&quot;: true,<br>  &quot;data&quot;: {<br>    &quot;id&quot;: 5,<br>    &quot;name&quot;: &quot;Laptop&quot;<br>  }<br>}</pre><p>Order Endpoint:</p><pre>POST /api/orders</pre><p>Response:</p><pre>{<br>  &quot;message&quot;: &quot;Order created&quot;<br>}</pre><p>Although each endpoint returns valid JSON, there is no consistency.</p><p>A frontend developer consuming these endpoints now has to remember:</p><ul><li>Customer responses contain data directly.</li><li>Product responses wrap data in a data property.</li><li>Order responses only contain a message.</li></ul><p>As applications grow, this inconsistency becomes difficult to maintain. Every consumer of the API must write special handling logic for different endpoints.</p><p>A standardized response structure solves this problem by making responses predictable.</p><p>For example, we could agree that every API response should contain:</p><ul><li>A success indicator.</li><li>A message describing the outcome.</li><li>A status code.</li><li>A data property containing the returned information.</li><li>An errors property containing additional error details when applicable.</li></ul><p>This is the primary purpose of a standard API response model: <strong>to make API communication predictable, reusable, and easier for consumers to understand.</strong></p><h3><strong>Understanding the Anatomy of an API Response</strong></h3><p>Although response structures vary between organizations, most APIs contain similar pieces of information.</p><p>Consider the following response:</p><pre>{<br>    &quot;success&quot;: true,<br>    &quot;statusCode&quot;: 200,<br>    &quot;message&quot;: &quot;Customer retrieved successfully&quot;,<br>    &quot;data&quot;: {<br>        &quot;id&quot;: 15,<br>        &quot;firstName&quot;: &quot;John&quot;,<br>        &quot;lastName&quot;: &quot;Doe&quot;,<br>        &quot;email&quot;: &quot;john@example.com&quot;<br>    },<br>    &quot;errors&quot;: null<br>}</pre><p>Each property serves a specific purpose.</p><h4>success</h4><p>The success property tells the client whether the operation completed successfully. This allows a client application to immediately understand the outcome without inspecting all other properties.</p><h4>statusCode</h4><p>This represents the HTTP status code associated with the response.</p><p>Common examples include:</p><ul><li>200 OK: The request was successfully processed.</li><li>201 Created: A new resource was successfully created.</li><li>400 Bad Request: The request contains invalid information.</li><li>401 Unauthorized: Authentication is required or has failed.</li><li>403 Forbidden: The client does not have permission to perform the operation.</li><li>404 Not Found: The requested resource does not exist.</li><li>500 Internal Server Error: An unexpected server-side error occurred.</li></ul><h4><strong>message</strong></h4><p>This provides a human-readable description of the operation’s outcome. Messages should be meaningful and should not expose sensitive implementation details.</p><h4>data</h4><p>This contains the actual information returned by the API.</p><p>For example, when retrieving a customer, it contains the customer details. When creating an account, it might contain the newly created account information.</p><p>Not every response will have data. For example, a failed request might return null in this property or an empty array.</p><h4>errors</h4><p>This contains additional information about errors encountered while processing a request.</p><p>For example, when a customer submits an invalid email address, the API can use this property to explain the validation failure.</p><h3>Success and Error Responses</h3><p>One of the biggest advantages of a standard response structure is consistency across successful and failed requests.</p><h4>Successful Response</h4><pre>{<br>    &quot;success&quot;: true,<br>    &quot;statusCode&quot;: 200,<br>    &quot;message&quot;: &quot;Customer retrieved successfully&quot;,<br>    &quot;data&quot;: {<br>        &quot;id&quot;: 23,<br>        &quot;firstName&quot;: &quot;Ben&quot;,<br>        &quot;lastName&quot;: &quot;Doe&quot;,<br>        &quot;email&quot;: &quot;ben@example.com&quot;<br>    },<br>    &quot;errors&quot;: null<br>}</pre><p>The client immediately knows:</p><ul><li>Request succeeded</li><li>Status Code returned</li><li>Customer data exists</li><li>A descriptive message is available</li><li>The fact that no error occurred</li></ul><h4>Failed response</h4><pre>{<br>    &quot;success&quot;: false,<br>    &quot;statusCode&quot;: 400,<br>    &quot;message&quot;: &quot;Customer information could not be validated&quot;,<br>    &quot;data&quot;: null,<br>    &quot;errors&quot;: [<br>        {<br>            &quot;field&quot;: &quot;FirstName&quot;,<br>            &quot;code&quot;: &quot;REQUIRED&quot;,<br>            &quot;message&quot;: &quot;First name is required&quot;<br>        },<br>        {<br>            &quot;field&quot;: &quot;Email&quot;,<br>            &quot;code&quot;: &quot;REQUIRED&quot;,<br>            &quot;message&quot;: &quot;Email address is required&quot;<br>        }<br>    ]<br>}</pre><p>The structure remains consistent, but the values differ depending on the outcome of the operation.</p><p>For successful operations, data contains the returned information, while errors is null.</p><p>For failed operations, data is null, while errors contains the details of the failure.</p><p>This gives API consumers a predictable way to process responses regardless of the endpoint being called.</p><h3>Creating a Generic API Response Model</h3><p>This is where our understanding of Generics becomes useful.</p><p>Instead of creating separate response classes for every data type, we can create one generic response class that accepts different types through a type parameter.</p><pre>public class ApiResponse&lt;T&gt;<br>{<br>    public bool Success { get; set; }<br><br>    public int StatusCode { get; set; }<br><br>    public string Message { get; set; } = string.Empty;<br><br>    public T? Data { get; set; }<br><br>    public List&lt;ApiError&gt;? Errors { get; set; }<br>}</pre><p>Some developers question why <strong>StatusCode </strong>property exists when HTTP already provides a status code.</p><p>In practice, many teams include it because:</p><ul><li>It makes responses self-describing.</li><li>It allows logging systems to inspect response content without reading HTTP metadata.</li><li>It provides a consistent contract across all responses.</li><li>It is easily accessible when working purely with serialized response objects.</li></ul><p>The important point is that it should always match the actual HTTP response code.</p><h3>Handling Error Responses</h3><p>To support structured errors, we can create a dedicated error model.</p><pre>public class ApiError<br>{<br>    public string Field { get; set; } = string.Empty;<br><br>    public string Code { get; set; } = string.Empty;<br><br>    public string Message { get; set; } = string.Empty;<br>}</pre><p>Each property serves a specific purpose.</p><ul><li>Field: Identifies the property responsible for the error.</li><li>Code: Provides a machine-readable error identifier.</li><li>Message: Provides a user-friendly explanation.</li></ul><h3>Using the Response Model in an ASP.NET Core API</h3><p>Suppose we have a Customer entity stored in a database and a CustomerDto used for API responses.</p><pre>public class Customer<br>{<br>    public int Id { get; set; }<br><br>    public string FirstName { get; set; } = string.Empty;<br><br>    public string LastName { get; set; } = string.Empty;<br><br>    public string Email { get; set; } = string.Empty;<br>}<br><br>public class CustomerDto<br>{ <br>    public string FirstName { get; set; } = string.Empty;<br><br>    public string LastName { get; set; } = string.Empty;<br><br>    public string Email { get; set; } = string.Empty;<br>}</pre><p>Behind the scenes, we have an existing ApplicationDbContext that contains the Customers table</p><pre>public class ApplicationDbContext : DbContext<br>{<br>    public DbSet&lt;Customer&gt; Customers =&gt; Set&lt;Customer&gt;();<br>}</pre><p>We then have a Customer Service responsible for retrieving customer data from the database.</p><pre>public interface ICustomerService<br>{<br>    Task&lt;CustomerDto?&gt; GetCustomerByIdAsync(int customerId);<br>}<br><br>public class CustomerService : ICustomerService<br>{<br>    private readonly ApplicationDbContext _dbContext;<br><br>    public CustomerService(ApplicationDbContext dbContext)<br>    {<br>        _dbContext = dbContext;<br>    }<br><br>    public async Task&lt;CustomerDto?&gt; GetCustomerByIdAsync(int customerId)<br>    {<br>        var customer = await _dbContext.Customers<br>            .AsNoTracking()<br>            .FirstOrDefaultAsync(c =&gt; c.Id == customerId);<br><br>        if (customer is null)<br>        {<br>            return null;<br>        }<br><br>        return new CustomerDto<br>        { <br>            FirstName = customer.FirstName,<br>            LastName = customer.LastName,<br>            Email = customer.Email<br>        };<br>    }<br>}</pre><p>And a controller that exposes responses to the client wrapped in the standardized response model</p><pre>[ApiController]<br>[Route(&quot;api/customers&quot;)]<br>public class CustomersController : ControllerBase<br>{<br>    private readonly ICustomerService _customerService;<br><br>    public CustomersController(ICustomerService customerService)<br>    {<br>        _customerService = customerService;<br>    }<br><br>    [HttpGet(&quot;{id:int}&quot;)]<br>    public async Task&lt;ActionResult&lt;ApiResponse&lt;CustomerDto&gt;&gt;&gt; GetCustomer(int id)<br>    {<br>        var customer = await _customerService.GetCustomerByIdAsync(id);<br><br>        if (customer is null)<br>        {<br>            return NotFound(new ApiResponse&lt;CustomerDto&gt;<br>            {<br>                Success = false,<br>                StatusCode = StatusCodes.Status404NotFound,<br>                Message = &quot;Customer not found&quot;,<br>                Data = null,<br>                Errors = null<br>            });<br>        }<br><br>        return Ok(new ApiResponse&lt;CustomerDto&gt;<br>        {<br>            Success = true,<br>            StatusCode = StatusCodes.Status200OK,<br>            Message = &quot;Customer retrieved successfully&quot;,<br>            Data = customer,<br>            Errors = null<br>        });<br>    }<br>}</pre><p>If the customer exists, the API returns:</p><pre>200 Ok<br><br>{<br>    &quot;success&quot;: true,<br>    &quot;statusCode&quot;: 200,<br>    &quot;message&quot;: &quot;Customer retrieved successfully&quot;,<br>    &quot;data&quot;: {<br>        &quot;id&quot;: 23,<br>        &quot;firstName&quot;: &quot;Ben&quot;,<br>        &quot;lastName&quot;: &quot;Doe&quot;,<br>        &quot;email&quot;: &quot;ben@example.com&quot;<br>    },<br>    &quot;errors&quot;: null<br>}</pre><p>If the customer does not exist, the API returns:</p><pre>404 Not Found<br><br>{<br>    &quot;success&quot;: false,<br>    &quot;statusCode&quot;: 404,<br>    &quot;message&quot;: &quot;Customer not found&quot;,<br>    &quot;data&quot;: null,<br>    &quot;errors&quot;: null<br>}</pre><h3>Conclusion</h3><p>When designing response models, consistency should be the primary goal.</p><p>Avoid introducing properties that provide little value simply because they might be useful later. Every property in the response contract should serve a clear purpose.</p><p>Ensure that all endpoints use the same response structure. If one endpoint returns responses differently from the rest, consumers lose many of the advantages that standardization provides.</p><p>Be deliberate about handling null values. In some situations, data may legitimately be null, such as when a resource is not found or when a request fails validation. The response should communicate this clearly.</p><p>Finally, always keep the response body aligned with the HTTP status code. If the API returns a 404 Not Found, the statusCode property should also be 404, and the response should clearly communicate that the operation was unsuccessful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2dbe7e6b0d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generics in C#: Understanding Their Purpose in .NET Applications]]></title>
            <link>https://benedictodoh.medium.com/generics-in-c-understanding-their-purpose-in-net-applications-a17820de307e?source=rss-771b70f7b31d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a17820de307e</guid>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Benedict Odoh]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 17:31:01 GMT</pubDate>
            <atom:updated>2026-11-18T17:31:01.691Z</atom:updated>
            <content:encoded><![CDATA[<p>As you work with C# and .NET, you will frequently encounter declarations such as:</p><pre>List&lt;Customer&gt;<br>List&lt;Transaction&gt;<br>ApiResponse&lt;Customer&gt;<br>ApiResponse&lt;Account&gt;</pre><p>You may have also wondered why C# allows us to put types inside angle brackets (&lt; &gt;). These declarations use a feature known as <strong>Generics</strong>.</p><p>Generics are one of the fundamental features of C# and are used extensively across the .NET ecosystem. They are used in collections, asynchronous programming, Entity Framework Core, dependency injection, repositories, services, and many other parts of application development.</p><p>The real value of generics becomes apparent when designing applications that work with different data types but need to maintain consistent behaviour.</p><p>Imagine developing a banking application that manages customers, accounts and transactions. Each entity has its own properties and business rules, but certain operations, such as retrieving records, storing results and handling responses, follow similar patterns.</p><p>Rather than implementing the same structure repeatedly for every entity, generics allow us to create reusable components while preserving the specific data types involved.</p><h3>Understanding the Problem Generics Solve</h3><p>Suppose we want to create a standard response structure for our banking application.</p><p>Whenever an API endpoint is called, we want to return information about whether the operation was successful and the data associated with it.</p><p>We might start by creating a response class for customers:</p><pre>public class CustomerResponse<br>{<br>    public bool Success { get; set; }<br>    public Customer? Data { get; set; }<br>}</pre><p>Later, we need to return transaction information, so we create another class:</p><pre>public class TransactionResponse<br>{<br>    public bool Success { get; set; }<br>    public Transaction? Data { get; set; }<br>}</pre><p>Looking at both classes, you will notice that their structures are almost identical. The only difference is the type of data they contain.</p><p>If we introduce an account response, we would have to create another class with the same structure.</p><p>This means we are repeating code unnecessarily.</p><p>Instead of creating a separate class for every entity, we could create one response class and specify the type of data it should contain whenever we use it.</p><pre>public class ApiResponse&lt;T&gt;<br>{<br>    public bool Success { get; set; }<br>    public string Message { get; set; } = string.Empty;<br>    public T? Data { get; set; }<br>}</pre><p>We can now use this same class for different entities:</p><pre>ApiResponse&lt;Customer&gt; customerResponse;<br><br>ApiResponse&lt;Transaction&gt; transactionResponse;<br><br>ApiResponse&lt;Account&gt; accountResponse;</pre><p>Instead of maintaining three different response classes, we have one reusable class that can accommodate different data types.</p><p><strong>This is the primary purpose of generics: writing reusable code that works with different data types without having to duplicate the implementation.</strong></p><h3>Understanding Generic Type Parameters</h3><p>In the below:</p><pre>public class ApiResponse&lt;T&gt;</pre><p>The T represents a generic type parameter. It is a placeholder for the actual type that will be supplied when the class is used.</p><p>For example:</p><pre>ApiResponse&lt;Customer&gt;</pre><p>means that T represents Customer.</p><p>The letter T is a naming convention, not a special keyword. You could use another name, such as TEntity, TRequest or TResponse, depending on what the type represents.</p><p>The important thing is that we do not need to decide the actual data type when creating the generic class. We can supply it when we use the class.</p><h3>Generic Methods</h3><p>You will often see generics used in custom classes rather than methods. However, Generics can also be applied to individual methods without making the entire class generic.</p><p>Consider an application where we frequently need to retrieve a record from a collection using its ID.</p><p>We could write a method specifically for customers:</p><pre>public Customer? GetCustomerById(<br>    List&lt;Customer&gt; customers,<br>    int id)<br>{<br>    return customers.FirstOrDefault(x =&gt; x.Id == id);<br>}</pre><p>If we need the same operation for accounts, we might write another method:</p><pre>public Account? GetAccountById(<br>    List&lt;Account&gt; accounts,<br>    int id)<br>{<br>    return accounts.FirstOrDefault(x =&gt; x.Id == id);<br>}</pre><p>Again, the implementation is almost identical. We are only changing the data type.</p><p>We can make the method reusable by introducing a generic type parameter:</p><pre>public T? GetById&lt;T&gt;(<br>    List&lt;T&gt; records,<br>    int id,<br>    Func&lt;T, int&gt; getId)<br>{<br>    return records.FirstOrDefault(x =&gt; getId(x) == id);<br>}</pre><p>We can now use the same method for customers and accounts:</p><pre>Customer? customer = GetById(<br>    customers,<br>    10,<br>    x =&gt; x.Id);<br><br>Account? account = GetById(<br>    accounts,<br>    20,<br>    x =&gt; x.Id);</pre><h3>Generic Interfaces</h3><p>Generics become particularly useful when designing reusable components in larger applications.</p><p>Consider a banking application with entities such as:</p><ul><li>Customer</li><li>Account</li><li>Transaction</li></ul><p>Each entity needs basic database operations, such as retrieving a record, retrieving all records, and adding a new record.</p><p>Without generics, we might create separate repository interfaces:</p><pre>public interface ICustomerRepository<br>{<br>    Task&lt;Customer?&gt; GetByIdAsync(int id);<br>    Task&lt;List&lt;Customer&gt;&gt; GetAllAsync();<br>}<br><br>public interface IAccountRepository<br>{<br>    Task&lt;Account?&gt; GetByIdAsync(int id);<br>    Task&lt;List&lt;Account&gt;&gt; GetAllAsync();<br>}</pre><p>Both interfaces define essentially the same operations. Instead, we can create one generic interface:</p><pre>public interface IRepository&lt;T&gt;<br>{<br>    Task&lt;T?&gt; GetByIdAsync(int id);<br>    Task&lt;List&lt;T&gt;&gt; GetAllAsync();<br>    Task AddAsync(T entity);<br>}</pre><p>We can then use it for different entities:</p><pre>IRepository&lt;Customer&gt;<br><br>IRepository&lt;Account&gt;<br><br>IRepository&lt;Transaction&gt;</pre><p>The interface remains the same, but the type supplied determines the entity it works with.</p><h3>Implementing a Generic Repository</h3><p>Having created our generic interface, we can implement it once.</p><p>Let’s use our banking application and demonstrate how the repository works with a Customer entity.</p><p>First, consider a simple Customer entity:</p><pre>public class Customer<br>{<br>    public int Id { get; set; }<br>    public string FirstName { get; set; } = string.Empty;<br>    public string LastName { get; set; } = string.Empty;<br>    public string Email { get; set; } = string.Empty;<br>}</pre><p>And usingAppDbContext which provides access to the database through Entity Framework Core:</p><pre>public class AppDbContext : DbContext<br>{<br>    public AppDbContext(DbContextOptions&lt;AppDbContext&gt; options)<br>        : base(options)<br>    {<br>    }<br><br>    public DbSet&lt;Customer&gt; Customers { get; set; }<br>}</pre><p>The Customers property represents the customer collection in the database.</p><p>Implementing the earlier created interface using Entity Framework Core:</p><pre>public class Repository&lt;T&gt; : IRepository&lt;T&gt;<br>    where T : class<br>{<br>    private readonly AppDbContext _context;<br>    private readonly DbSet&lt;T&gt; _dbSet;<br><br>    public Repository(AppDbContext context)<br>    {<br>        _context = context;<br>        _dbSet = _context.Set&lt;T&gt;();<br>    }<br><br>    public async Task&lt;T?&gt; GetByIdAsync(int id)<br>    {<br>        return await _dbSet.FindAsync(id);<br>    }<br><br>    public async Task&lt;List&lt;T&gt;&gt; GetAllAsync()<br>    {<br>        return await _dbSet.ToListAsync();<br>    }<br><br>    public async Task AddAsync(T entity)<br>    {<br>        await _dbSet.AddAsync(entity);<br>        await _context.SaveChangesAsync();<br>    }<br>}</pre><p>From the above, _context.Set&lt;T&gt;() or _dbSet, EF Core uses it to access the database set associated with the supplied entity type.</p><p>For example, when T is Customer:</p><pre>_context.Set&lt;Customer&gt;()</pre><p>We can proceed to use the repository by creating a customer-specific version of the generic repository.</p><p>Assuming the below entity exists and is registered in the AppDbContext class:</p><pre>public class Customer<br>{<br>    public int Id { get; set; }<br>    public string FirstName { get; set; } = string.Empty;<br>    public string LastName { get; set; } = string.Empty;<br>    public string Email { get; set; } = string.Empty;<br>}<br><br><br>public class AppDbContext : DbContext<br>{<br>    public DbSet&lt;Customer&gt; Customers { get; set; }<br><br>    public AppDbContext(DbContextOptions&lt;AppDbContext&gt; options)<br>        : base(options)<br>    {<br>    }<br>}</pre><p>Registration:</p><pre>builder.Services.AddScoped(<br>    typeof(IRepository&lt;&gt;),<br>    typeof(Repository&lt;&gt;));</pre><p>The above tells ASP.NET Core:</p><blockquote><em>Whenever someone requests </em><em>IRepository&lt;Customer&gt;, create a </em><em>Repository&lt;Customer&gt;.</em></blockquote><blockquote><em>Whenever someone requests </em><em>IRepository&lt;Account&gt;, create a </em><em>Repository&lt;Account&gt;.</em></blockquote><p>Injecting the repository interface into a custom service:</p><pre>public class CustomerService<br>{<br>    private readonly IRepository&lt;Customer&gt; _customerRepository;<br><br>    public CustomerService(IRepository&lt;Customer&gt; customerRepository)<br>    {<br>        _customerRepository = customerRepository;<br>    }<br><br>    public async Task&lt;Customer?&gt; GetCustomerAsync(int id)<br>    {<br>        return await _customerRepository.GetByIdAsync(id);<br>    }<br><br>    public async Task&lt;List&lt;Customer&gt;&gt; GetCustomersAsync()<br>    {<br>        return await _customerRepository.GetAllAsync();<br>    }<br><br>    public async Task CreateCustomerAsync(Customer customer)<br>    {<br>        await _customerRepository.AddAsync(customer);<br>    }<br>}</pre><p>You can then proceed to inject the service into a controller to expose it to clients.</p><pre>[ApiController]<br>[Route(&quot;api/customers&quot;)]<br>public class CustomersController : ControllerBase<br>{<br>    private readonly CustomerService _customerService;<br><br>    public CustomersController(CustomerService customerService)<br>    {<br>        _customerService = customerService;<br>    }<br><br>    [HttpGet(&quot;{id}&quot;)]<br>    public async Task&lt;ActionResult&lt;Customer&gt;&gt; GetCustomer(int id)<br>    {<br>        var customer = await _customerService.GetCustomerAsync(id);<br><br>        if (customer == null)<br>            return NotFound();<br><br>        return Ok(customer);<br>    }<br>}</pre><p>The above flow can be summarized:</p><p>When a request reaches CustomersController:</p><ol><li>ASP.NET Core creates CustomersController.</li><li>It sees that CustomerService is required.</li><li>It creates CustomerService.</li><li>It sees that CustomerService requires IRepository&lt;Customer&gt;.</li><li>Because of this registration:<br>builder.Services.AddScoped(typeof(IRepository&lt;&gt;),typeof(Repository&lt;&gt;));</li><li>ASP.NET Core creates:<br>new Repository&lt;Customer&gt;(dbContext)</li><li>The repository receives the AppDbContext.</li><li>The service receives the repository.</li><li>The controller receives the service.</li></ol><h3>Generic Constraints</h3><p>Generic constraints restrict the types that can be used as generic type arguments. They provide <strong>compile-time type safety</strong> and allow generic code to rely on specific characteristics of a type.</p><p>In the repository example:</p><pre>public class Repository&lt;T&gt; : IRepository&lt;T&gt;<br>    where T : class<br>{<br>}</pre><p>the constraint:</p><pre>where T : class</pre><p>ensures that T is a <strong>reference type</strong>. This is required because Entity Framework Core&#39;s DbSet&lt;T&gt; and DbContext.Set&lt;T&gt;() work with entity classes rather than value types.</p><p>Constraints enable generic code to:</p><ul><li>Restrict invalid types from being used.</li><li>Access members or functionality guaranteed by a base class or interface.</li><li>Improve compile-time validation.</li><li>Support framework requirements such as EF Core’s entity constraints.</li></ul><p>Common Generic Constraints include:</p><h4>Reference Type</h4><pre>where T : class</pre><p>T must be a class.</p><pre>Repository&lt;Customer&gt; repository; // Valid<br>Repository&lt;int&gt; repository;      // Invalid</pre><h4>Value Type</h4><pre>where T : struct</pre><p>T must be a value type.</p><pre>Calculator&lt;int&gt; calculator;      // Valid<br>Calculator&lt;string&gt; calculator;   // Invalid</pre><h4>Parameterless Constructor</h4><pre>where T : new()</pre><p>T must have a public parameterless constructor.</p><pre>T instance = new T();</pre><h4>Base Class</h4><pre>where T : Person</pre><p>T must inherit from Person.</p><pre>class Customer : Person { }<br><br>Repository&lt;Customer&gt; repository; // Valid</pre><h4>Interface</h4><pre>where T : IEntity</pre><p>T must implement IEntity.</p><pre>public interface IEntity<br>{<br>    int Id { get; set; }<br>}</pre><p>This allows the generic type to safely access the Id property.</p><h3>Multiple Constraints</h3><p>Multiple constraints can be combined:</p><pre>public class Repository&lt;T&gt;<br>    where T : class, IEntity, new()<br>{<br>}</pre><p>This requires T to:</p><ol><li>Be a reference type (class).</li><li>Implement IEntity.</li><li>Have a parameterless constructor (new()).</li></ol><h3>Conclusion</h3><p>Generics are not simply a C# syntax feature that requires memorising angle brackets and type parameters. They solve a practical problem in application development: <strong>how to avoid repeating the same implementation when working with different data types.</strong></p><p>As we have seen, we can use generics to create reusable response classes, methods, interfaces and implementations.</p><p>The key concepts to remember are:</p><ol><li><strong>Generic type parameters:</strong> Placeholders that allow us to supply a data type when using a component.</li><li><strong>Generic classes:</strong> Reusable classes that can work with different types.</li><li><strong>Generic methods:</strong> Reusable methods that can perform the same operation on different types.</li><li><strong>Generic interfaces:</strong> Reusable contracts that can be implemented for different types.</li><li><strong>Generic constraints:</strong> Rules that specify which types a generic component can accept.</li></ol><p>The next time you encounter something like:</p><pre>IRepository&lt;Customer&gt;</pre><p>think of it as a reusable repository contract that has been configured to work with customers.</p><p>That is the central idea behind generics: write common functionality once, reuse it across different data types, and let C# maintain type safety along the way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a17820de307e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Tuple Deconstruction in C#]]></title>
            <link>https://benedictodoh.medium.com/understanding-tuple-deconstruction-in-c-69c7debfec58?source=rss-771b70f7b31d------2</link>
            <guid isPermaLink="false">https://medium.com/p/69c7debfec58</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Benedict Odoh]]></dc:creator>
            <pubDate>Sat, 31 Oct 2026 14:05:27 GMT</pubDate>
            <atom:updated>2026-10-31T14:05:27.076Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently discovered the following syntax that caught my attention in my company’s enterprise codebase:</p><pre>var (data, error) = ProcessData();</pre><p>What’s fascinating about this is that it does not follow the common convention of initializing and assigning values to variables. My quick research led me to the concept called <strong>deconstruction</strong>, a fancy word for a quirky syntax. But before we dive into what it means, we need to first understand what a tuple is.</p><h3>What is a Tuple?</h3><p>A tuple in C# is a data structure that allows you to group multiple values, potentially of different data types, into a single object without creating a dedicated class or object.</p><p>For example, imagine you have a method that needs to return an employee’s name, age, and salary. Traditionally, you might create a class or return an object. However, a tuple provides a simpler alternative.</p><pre>var employee = (&quot;John&quot;, 30, 250000m);<br><br>Console.WriteLine(employee.Item1); // John<br>Console.WriteLine(employee.Item2); // 30<br>Console.WriteLine(employee.Item3); // 250000</pre><p>By default, we access the individual values using Item1, Item2, and Item3. This default approach is called <em>accessing tuples by their position</em>. However, we can make this more readable by naming the tuple elements:</p><pre>var employee = (<br>    Name: &quot;John&quot;,<br>    Age: 30,<br>    Salary: 250000m<br>);<br><br>Console.WriteLine(employee.Name);<br>Console.WriteLine(employee.Age);<br>Console.WriteLine(employee.Salary);</pre><h3>What is Tuple Deconstruction?</h3><p>Tuple deconstruction is the process of unpacking the individual elements of a tuple into separate variables.</p><p>Instead of accessing each element through its name or position, we can extract all the values into individual variables in one statement.</p><p>Consider the previous example:</p><pre>var employee = (<br>    Name: &quot;John&quot;,<br>    Age: 30,<br>    Salary: 250000m<br>);<br><br>// Tuple deconstruction<br>var (name, age, salary) = employee;<br><br>Console.WriteLine(name);   // John<br>Console.WriteLine(age);    // 30<br>Console.WriteLine(salary); // 250000</pre><p>So C# reads the data from <strong>employee</strong>, extracts the tuple’s three elements, and assigns them to <strong>name</strong>, <strong>age</strong>, and <strong>salary</strong>, respectively.</p><p>Tuple deconstruction follows a core principle: <strong>the order of the variables must correspond to the order of the tuple elements.</strong></p><p>For example, assigning the below to <strong>employee</strong>:</p><pre>var (salary, name, age) = employee;</pre><p>This is valid C# syntax, but the values will be assigned incorrectly because deconstruction follows position rather than matching element names.</p><h3>Deconstructing a Tuple Directly</h3><p>You can create and deconstruct a tuple in the same statement.</p><pre>var (name, age, department) = (&quot;John&quot;, 30, &quot;IT&quot;);<br><br>Console.WriteLine(name);<br>Console.WriteLine(age);<br>Console.WriteLine(department);</pre><p>This is particularly useful when you need the individual values immediately and do not need to retain the original tuple.</p><h3>Deconstruction with Existing Variables</h3><p>We have seen how we have used <strong>var </strong>to declare new variables during deconstruction. C# also allows us to deconstruct a tuple into variables that have already been declared.</p><pre>string name;<br>int age;<br>decimal salary;<br><br>var employee = (&quot;John&quot;, 30, 250000m);<br><br>(name, age, salary) = employee;</pre><p>This is useful when variables have been declared earlier in a method and you want to assign tuple values to them later.</p><h3>Discarding Unwanted Tuple Elements</h3><p>Sometimes, a method may return values you don’t need for the current operation. C# provides the discard operator (_) for ignoring values during deconstruction.</p><pre>var employee = (<br>    Name: &quot;John&quot;,<br>    Age: 30,<br>    Salary: 250000m<br>);<br><br>var (name, _, salary) = employee;<br><br>Console.WriteLine(name);<br>Console.WriteLine(salary);</pre><p>The underscore tells the compiler that we do not need the second value (Age).</p><h3>Returning Tuples from Methods and Deconstructing Them</h3><p>One of the most practical applications of tuples is returning multiple values from a method.</p><p>Traditionally, a C# method returns a single value. When you need multiple results, you might create a custom class, use out parameters, or return a tuple.</p><p>Consider a method that retrieves an employee’s details:</p><pre>public static (string Name, int Age, decimal Salary)<br>    GetEmployee()<br>{<br>    return (&quot;John&quot;, 30, 250000m);<br>}</pre><p>We can call this method and access its returned values individually:</p><pre>var employee = GetEmployee();<br><br>Console.WriteLine(employee.Name); // John<br>Console.WriteLine(employee.Age); // 30<br>Console.WriteLine(employee.Salary); //250000</pre><p>However, we can simplify this using tuple deconstruction:</p><pre>var (name, age, salary) = GetEmployee();<br><br>Console.WriteLine(name);<br>Console.WriteLine(age);<br>Console.WriteLine(salary);</pre><h4>Practical .NET API Example</h4><p>Imagine you are developing an API and need to validate a customer’s account before processing a transaction.</p><p>The below method is created to return both the validation result and a descriptive message.</p><pre>public (bool IsValid, string Message) ValidateAccount(<br>    int accountNumber)<br>{<br>    if (accountNumber &lt;= 0)<br>    {<br>        return (false, &quot;Invalid account number.&quot;);<br>    }<br><br>    return (true, &quot;Account validation successful.&quot;);<br>}</pre><p>You can consume the method using tuple deconstruction:</p><pre>var (isValid, message) = ValidateAccount(request.AccountNo);<br><br>if (!isValid)<br>{<br>    Console.WriteLine(message);<br>    return;<br>}<br><br>Console.WriteLine(message);<br><br>// Continue transaction processing</pre><p>Rather than defining a separate class for a simple two-value result, a tuple provides a lightweight alternative.</p><p>However, for complex API responses, reusable business objects, or responses that require validation and documentation, dedicated DTOs are generally more appropriate.</p><h3>Conclusion</h3><p>Tuple deconstruction makes working with multiple values in C# cleaner and more readable. It is particularly useful when consuming methods that return tuples and avoiding unnecessary temporary variables.</p><p>As a .NET developer, you will commonly encounter it when working with methods that return multiple results, LINQ operations, and APIs or libraries that expose tuple-based return values.</p><p>The key is understanding when a tuple is sufficient and when a dedicated class, struct, or DTO provides a better design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69c7debfec58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Stash: Temporarily Saving Development Work Without Committing It]]></title>
            <link>https://benedictodoh.medium.com/git-stash-temporarily-saving-development-work-without-committing-it-7ea71babba99?source=rss-771b70f7b31d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ea71babba99</guid>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Benedict Odoh]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 16:00:55 GMT</pubDate>
            <atom:updated>2026-10-02T16:01:30.113Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s world of software development, everything is seemingly urgent. You can be working on one urgent task and be asked to focus more effort on another urgent task, then later be asked to revisit and modify some changes from the previous urgent task. These different urgent implementations will most likely not move to the production environment at the same time; hence the need to address them in separate branches. But there may be instances where you’re not quite ready to commit your changes. This is where <strong>Git Stash</strong> comes in.</p><h3>What Is Git Stash?</h3><p>git stash allows you to temporarily save your uncommitted changes without creating a commit. It is particularly useful when you need to switch branches but your current work is not ready to be committed.</p><p>Imagine you’re working on a customer transfer feature:</p><pre>git switch feature/customer-transfer</pre><p>You’ve modified: AccountsController.cs,TransferService.cs, and TransferRequest.cs but the feature isn’t complete.</p><p>Suddenly, you’re asked to fix an urgent issue on another branch. Instead of committing incomplete work, you can stash it:</p><pre>git stash</pre><p>Git temporarily stores your changes and restores your working directory to a clean state.</p><p>You can now switch branches:</p><pre>git switch bugfix/transaction-timeout</pre><p>After completing the urgent work, you can return to your feature branch and restore the changes you stashed.</p><p>That is the core idea behind Git Stash:</p><blockquote>Temporarily put your unfinished changes aside so you can work on something else.</blockquote><h3>Checking Your Working Directory</h3><p>Before using stash, understand what Git currently sees:</p><pre>git status</pre><p>You might see:</p><pre>On branch feature/customer-transfer <br><br>Changes not staged for commit: <br>  modified: AccountsController.cs <br>  modified: TransferService.cs</pre><p>These are uncommitted changes. If you’re not ready to commit them, stash is an option.</p><h3>Stashing Your Changes</h3><p>The simplest command is:</p><pre>git stash</pre><p>Git stores your changes and leaves your working directory clean.</p><p>You can verify this with:</p><pre>git status</pre><p>You should now see:</p><pre>On branch feature/customer-transfer <br>nothing to commit, working tree clean</pre><p>Your changes haven’t been deleted. They are stored in Git’s stash.</p><p>For practical development, it is highly recommended to give your stash a description:</p><pre>git stash push -m &quot;Customer transfer implementation&quot;</pre><p>This makes it easier to identify later.</p><h3>Including Untracked Files</h3><p>There is an important distinction between <strong>modified tracked files</strong> and <strong>untracked files</strong>.</p><p>Suppose you create: TransferValidator.cs</p><p>Git considers this an untracked file.</p><p>A normal:</p><pre>git stash</pre><p>doesn’t include untracked files by default.</p><p>The best approach is to use:</p><pre>git stash push -u -m &quot;Customer transfer implementation&quot;</pre><p>The -u means --include-untracked.</p><h3>Viewing Your Stashes</h3><p>You can see your stored stashes with:</p><pre>git stash list</pre><p>If you have multiple stashes, they will be arranged like:</p><pre>stash@{0}: On feature/customer-transfer: Customer transfer implementation <br>stash@{1}: On feature/account-opening: Account validation <br>stash@{2}: On bugfix/payment: Payment validation</pre><p>Git maintains these as a collection of stash entries.</p><p>The most recent stash is normally: stash@{0} while older entries have higher numbers.</p><p>You can inspect a stash before restoring it:</p><pre>git stash show -p stash@{0}</pre><p>The -p displays the actual changes contained in the stash.</p><h3>Restoring Stashed Changes</h3><p>Once you return to your original branch:</p><pre>git switch feature/customer-transfer</pre><p>you can restore your changes.</p><p>There are two commands you should understand: <strong>git stash apply </strong>and <strong>git stash pop</strong></p><p>apply restores the changes <strong>but keeps the stash</strong>:</p><pre>git stash apply stash@{0}</pre><p>This is useful when you want to retain the stash as a backup.</p><p>pop restores the changes <strong>and removes the stash entry if the operation succeeds</strong>:</p><pre>git stash pop stash@{0}</pre><h3>Applying a Specific Stash</h3><p>You aren’t limited to the most recent stash. Suppose:</p><pre>git stash list</pre><p>returns:</p><pre>stash@{0}: On feature/payment: Payment validation <br>stash@{1}: On feature/customer-transfer: Transfer implementation</pre><p>You can restore the customer transfer work specifically:</p><pre>git stash apply stash@{1}</pre><p>This is especially useful when you have multiple unfinished tasks stored in your stash.</p><h3>Stash Conflicts</h3><p>Stashing doesn’t eliminate the possibility of merge conflicts.</p><p>For example, you stash a change to: <strong>TransferService.cs</strong></p><p>Later, the same section of the file changes. When you run:</p><pre>git stash pop</pre><p>Git may report:</p><pre>CONFLICT (content): Merge conflict in TransferService.cs</pre><p>You resolve this just as you would resolve a normal Git merge conflict.</p><p>After resolving the file:</p><pre>git add TransferService.cs</pre><p>Then verify:</p><pre>git status</pre><p>It is important to note that <strong>stash only stores and reapplies your changes; it doesn’t guarantee that those changes will apply cleanly to the current version of your code. </strong>As a developer, you are responsible for ensuring that they do apply cleanly as intended.</p><h3>Removing Stashes</h3><p>If you no longer need a stash, remove it with:</p><pre>git stash drop stash@{0}</pre><p>If you want to remove all stash entries:</p><pre>git stash clear</pre><p>Be careful with git stash clear because it removes the entire stash collection.</p><h3>Conclusion</h3><p>Git Stash is a simple but useful tool for temporarily putting aside uncommitted work when you need a clean working directory.</p><p>The commands worth becoming comfortable with are:</p><pre>git stash push -u -m &quot;Description&quot; git stash list <br>git stash show -p stash@{0} <br>git stash apply stash@{0} <br>git stash pop stash@{0} <br>git stash drop stash@{0}</pre><p>The main concept to remember is straightforward: <strong>commit when you want to record your work; stash when you temporarily need to put that work aside.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ea71babba99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ADO.NET in .NET: A Guide to Building Data Access with SQL Server]]></title>
            <link>https://benedictodoh.medium.com/ado-net-in-net-a-guide-to-building-data-access-with-sql-server-83bc783410f3?source=rss-771b70f7b31d------2</link>
            <guid isPermaLink="false">https://medium.com/p/83bc783410f3</guid>
            <dc:creator><![CDATA[Benedict Odoh]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 08:01:02 GMT</pubDate>
            <atom:updated>2026-09-18T08:01:02.562Z</atom:updated>
            <content:encoded><![CDATA[<p>When building a .NET application that needs to store or retrieve information, at some point the application has to communicate with a database. An ASP.NET Core Web API may receive an HTTP request from a client, but the API itself does not magically know how to retrieve a customer from SQL Server. Something has to establish a connection to the database, send SQL commands, retrieve the results, and convert those results into objects that the application can work with. This is where <strong>ADO.NET</strong> comes in.</p><p>ADO.NET is one of the foundational data-access technologies in the .NET ecosystem. It provides the classes and interfaces required for applications to communicate with relational databases and other data sources. Although developers working with <strong>Entity Framework Core</strong> or <strong>Dapper</strong> may not interact directly with many ADO.NET classes, those technologies build upon the same underlying concepts. Understanding ADO.NET therefore gives you a much better understanding of what actually happens when a .NET application communicates with a database.</p><p>In this article, we will start from the fundamentals and gradually build toward a practical ASP.NET Core Web API that uses ADO.NET to communicate with SQL Server.</p><blockquote>A heads up. This is gonna be a long read but hopefully it’s worth it! I have written a brief article on SQL Connection that is more straighforward which can be found <a href="https://benedictodoh.medium.com/a-guide-to-using-sqlconnection-in-net-e830bc3f56a1">here</a>. So if you are time pressed you may visit that.</blockquote><h3>What is ADO.NET?</h3><p>ADO.NET is a collection of .NET APIs for working with data sources.</p><p>In a typical SQL Server application, the basic flow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*v94w09uyVS29FhaPDbNSDw.png" /></figure><p>Suppose a client sends: GET /api/customers/10</p><p>The request eventually reaches a service responsible for retrieving the customer. That service may use ADO.NET to:</p><ol><li>Create a database connection.</li><li>Open the connection.</li><li>Create a SQL command.</li><li>Add parameters to the command.</li><li>Execute the command.</li><li>Read the returned data.</li><li>Convert the database record into a C# object.</li><li>Return that object to the API controller.</li></ol><p>The important thing to understand is that <strong>ADO.NET does not replace SQL Server</strong>. SQL Server remains the database while ADO.NET is the .NET-side technology used to communicate with the database.</p><h3>ADO.NET Is Provider-Based</h3><p>One of the most important concepts to understand is that ADO.NET itself is not specifically a SQL Server technology.</p><p>ADO.NET provides the low-level APIs and common abstractions that .NET applications use to communicate with data sources. A <strong>data provider</strong> then implements the database-specific functionality required to connect to a particular database system.</p><p>For SQL Server, the modern provider is Microsoft.Data.SqlClient.</p><p>It provides classes such as SqlConnection, SqlCommand, SqlDataReader, SqlTransaction, SqlParameter, etc.</p><p>Microsoft describes Microsoft.Data.SqlClient as the supported .NET data provider for SQL Server and Azure SQL and recommends it for new development for .NET 10 frameworks +.</p><p>This distinction is important because you will often see older tutorials using:</p><pre>using System.Data.SqlClient;</pre><p>That namespace belongs to the older SQL Server provider. For modern .NET applications, prefer:</p><pre>using Microsoft.Data.SqlClient;</pre><h3>ADO.NET, Dapper, and Entity Framework Core</h3><p>ADO.NET, Dapper, and Entity Framework Core can all be used to access a database, but they operate at different levels of abstraction.</p><p>ADO.NET is a <strong>low-level data-access API</strong>. You write the SQL yourself, create commands, add parameters, execute them, read the results, and map database rows to C# objects manually.</p><p>Dapper is a lightweight <strong>micro-ORM</strong> built on top of ADO.NET. You still write the SQL, but Dapper reduces much of the repetitive code involved in creating commands, executing queries, and mapping rows to objects.</p><p>Entity Framework Core is a full <strong>object-relational mapper</strong>, or ORM. It allows you to work primarily with C# entities and a database context, while EF Core generates much of the SQL, tracks entity changes, and handles object-to-row mapping for you.</p><p>The abstraction levels can be summarized like this:</p><p>Entity Framework Core</p><ul><li>Higher-level ORM</li><li>Works mainly with entities and DbContext</li></ul><p>Dapper</p><ul><li>Lightweight micro-ORM</li><li>You write SQL; Dapper handles execution and mapping</li></ul><p>ADO.NET</p><ul><li>Low-level data-access API</li><li>You manage SQL, commands, parameters, readers, and mapping</li></ul><h3>The Core ADO.NET Classes</h3><h4>SqlConnection</h4><p>SqlConnection represents the connection between your .NET application and SQL Server. You use it to open communication with the database before executing a query or command.</p><pre>await using var connection = <br>    new SqlConnection(connectionString); <br><br>await connection.OpenAsync();</pre><h4>SqlCommand</h4><p>SqlCommand represents the SQL statement or stored procedure you want SQL Server to execute.</p><pre>await using var command = <br>    new SqlCommand( &quot;SELECT Id, Name FROM Customers&quot;, connection);</pre><p>A command always works with an open connection.</p><h4>SqlParameter</h4><p>SqlParameter allows you to pass values safely into SQL statements.</p><pre>command.Parameters.Add(&quot;@CustomerId&quot;, SqlDbType.Int) <br>    .Value = customerId;</pre><p>Parameters help prevent SQL injection and ensure that values are sent to SQL Server with the expected data type.</p><h4>SqlDataReader</h4><p>SqlDataReader reads rows returned by a query.</p><pre>await using var reader = <br>    await command.ExecuteReaderAsync(); <br><br>while (await reader.ReadAsync()) { var name = reader.GetString( reader.GetOrdinal(&quot;Name&quot;)); }</pre><p>A data reader processes results sequentially, one row at a time.</p><h4>SqlTransaction</h4><p>SqlTransaction groups multiple database operations into a single unit of work.</p><pre>await using var transaction = <br>    await connection.BeginTransactionAsync();</pre><p>If every operation succeeds, you commit the transaction. If one operation fails, you roll it back.</p><p>Transactions are especially important when several changes must either all succeed or all fail.</p><h3>The Three Main Execution Methods</h3><p>There are three main execution methods along with their async variants. The command execution method you choose depends on what your SQL statement returns. Non-async methods are simple, straightforward, but block the thread. Async methods are better for scalable, responsive apps.</p><h4><strong>ExecuteReader</strong> / <strong>ExecuteReaderAsync</strong></h4><ul><li>Use when the query returns multiple rows or columns.</li><li><strong>Sync:</strong> Blocks until all rows are ready.</li><li><strong>Async:</strong> Returns a Task&lt;SqlDataReader&gt;; you await it, freeing the thread. It supports CancellationToken for better control in long-running queries.</li></ul><pre>// Sync<br>using var reader = command.ExecuteReader();<br>while (reader.Read())<br>{<br>    Console.WriteLine(reader[&quot;Name&quot;]);<br>}<br><br>// Async<br>await using var reader = await command.ExecuteReaderAsync();<br>while (await reader.ReadAsync())<br>{<br>    Console.WriteLine(reader[&quot;Name&quot;]);<br>}</pre><p>Typical use cases include:</p><pre>SELECT Id, Name, Email <br>FROM Customers;</pre><h4>ExecuteScalar / ExecuteScalarAsync</h4><ul><li>Use when the query returns a single value (first column of the first row).</li><li>Sync: Blocks until the value is retrieved.</li><li>Async: Returns a Task&lt;object&gt;; you await it.</li></ul><pre>// Sync<br>int count = (int)command.ExecuteScalar();<br><br>// Async<br>int count = (int)await command.ExecuteScalarAsync();</pre><p>Typical use cases include:</p><pre>SELECT COUNT(*) <br>FROM Customers;</pre><p>Or:</p><pre>SELECT Id <br>FROM Customers <br>WHERE Email = @Email;</pre><h4>ExecuteNonQuery / ExecuteNonQueryAsync</h4><ul><li>Use when the command changes data but does not return a result set. That is, it does not return rows, e.g., INSERT, UPDATE, DELETE.</li><li><strong>Sync:</strong> Blocks until the command finishes, returns affected row count.</li><li><strong>Async:</strong> Returns a Task&lt;int&gt;; you await it.</li></ul><pre>// Sync<br>int rowsAffected = command.ExecuteNonQuery();<br><br>// Async<br>int rowsAffected = await command.ExecuteNonQueryAsync();</pre><p>Typical use cases include:</p><pre>INSERT INTO Customers (...) <br>VALUES (...);<br><br>UPDATE Customers <br>SET Email = @Email <br>WHERE Id = @Id;<br><br>DELETE FROM Customers <br>WHERE Id = @Id;</pre><p>The method returns the number of rows affected.</p><h3>ADO.NET Sequence of Operation</h3><p>A typical ADO.NET operation follows this sequence:</p><ol><li>Read the connection string.</li><li>Create a SqlConnection.</li><li>Open the connection.</li><li>Create a SqlCommand.</li><li>Add any required SqlParameter objects.</li><li>Execute the command.</li><li>Read or process the result.</li><li>Map the result to a C# object.</li><li>Dispose the database resources.</li></ol><p>Once this sequence becomes familiar, the individual ADO.NET classes are much easier to understand.</p><h3>Connecting to SQL Server</h3><p>SqlConnection represents a connection to SQL Server. Think of it as the communication channel between your application and the database.</p><p>A simple connection looks like this:</p><pre>using Microsoft.Data.SqlClient; <br><br>var connectionString = <br>    &quot;Server=localhost;<br>    Database=BankingDb;<br>    Trusted_Connection=True;<br>    TrustServerCertificate=True&quot;; <br><br><br>// Creating the object<br>using var connection = new SqlConnection(connectionString); <br><br>// Opening the connection<br>await connection.OpenAsync();</pre><p>At this point, the application has established a database connection.</p><p>However, creating the object and opening the connection are two different operations. Hence why you see we explicitly did both actions.</p><p>After the database operation has completed, the connection should be disposed. This is why you will commonly see:</p><pre>await using var connection = new SqlConnection(connectionString);</pre><p>Or:</p><pre>using var connection = new SqlConnection(connectionString);</pre><p>The using pattern ensures that the connection is properly disposed even if an exception occurs.</p><h3>Understanding the Connection Strings</h3><p>The connection string tells the provider where and how to connect to SQL Server.</p><p>For example:</p><pre>{<br>  &quot;ConnectionStrings&quot;: {<br>    &quot;DefaultConnection&quot;: &quot;Server=localhost;Database=BankingDb;Trusted_Connection=True;TrustServerCertificate=True&quot;<br>  }<br>}</pre><ul><li>Server=localhost: identifies the SQL Server instance.</li><li>Database=BankingDb: specifies the database to use.</li><li>Trusted_Connection=True: indicates Windows authentication.</li></ul><p>For SQL standard authentication, you might instead have something conceptually like:</p><pre>Server=localhost; <br>Database=BankingDb; <br>User Id=app_user; <br>Password=********;</pre><p>In a real application, sensitive credentials should not be hardcoded into C# source code or committed to source control.</p><p>Instead, configuration should be supplied through mechanisms such as environment variables, secret stores, or managed identity depending on the deployment environment.</p><h3>Sending Instructions to the Database via SqlCommand</h3><p>Creating a connection does not retrieve any data. We need something that tells SQL Server what we want it to do. That is the responsibility of SqlCommand.</p><p>For example:</p><pre>await using var command = <br>    new SqlCommand( &quot;SELECT Id, Name, Email FROM Customers&quot;, connection);</pre><p>The command contains two important pieces: SQL statement and Database Connection.</p><p>You can then execute the command via:</p><pre>await using var reader = await command.ExecuteReaderAsync();</pre><h3>Using ExecuteReader to retrieve rows of data</h3><p>ExecuteReaderAsync() is used when we need to return rows of data.</p><p>For example:</p><pre>await using var command = <br>      new SqlCommand( &quot;SELECT Id, Name, Email FROM Customers&quot;, connection); <br><br>await using var reader = await command.ExecuteReaderAsync();</pre><p>The result is a SqlDataReader. A SqlDataReader provides forward-only access to the result set. It is particularly useful when processing large result sets because the data can be consumed sequentially instead of loading the entire result into memory.</p><p>The corresponding SQL script is:</p><pre>SELECT Id, Name, Email <br>FROM Customers;</pre><h3>Reading the Results of a Query via SqlReader</h3><p>Consider this SQL query:</p><pre>SELECT Id, Name, Email <br>FROM Customers;</pre><p>The database may return tens, hundreds or thousands rows of data. The SqlDataReader allows your application to move through those rows.</p><pre>while (await reader.ReadAsync()) {<br>  var id = reader.GetInt32(reader.GetOrdinal(&quot;Id&quot;));<br>  var name = reader.GetString(reader.GetOrdinal(&quot;Name&quot;));<br>  var email = reader.GetString(reader.GetOrdinal(&quot;Email&quot;));<br>  Console.WriteLine($&quot;{id} - {name} - {email}&quot;);<br>}</pre><p>ReadAsync() moves the reader to the next row.</p><p>You can think of it as: ReadAsync() → Customer 1 → ReadAsync() → Customer 2 → ReadAsync() → Customer 3 ReadAsync() → … → No more rows</p><p>This is why we commonly see:</p><pre>while (await reader.ReadAsync())<br>{<br>    // process current row<br>}</pre><h4>Common SqlDataReader Methods for Column Access</h4><p>When working with SqlDataReader, you often need to extract values from database columns in a safe and efficient way. These methods provide different ways to read data by type, handle NULL values, and ensure your code remains clear and maintainable. They form the foundation for mapping raw database results into meaningful C# objects.</p><p><strong>GetOrdinal()</strong></p><ul><li>Finds the column’s index by its name. This is useful because you don’t have to hardcode column positions (like reader.GetInt32(0)), which makes your code more readable and less error-prone if the query changes.</li><li>Edge case: If the column name is misspelled or doesn’t exist, GetOrdinal() will throw an exception.</li></ul><pre>int idOrdinal = reader.GetOrdinal(&quot;Id&quot;);<br>int id = reader.GetInt32(idOrdinal);</pre><p><strong>GetInt32()</strong></p><ul><li>Reads a column as an int. Use when you’re sure the column is an integer.</li><li>Edge case: Throws an exception if the column is NULL or not an integer.</li></ul><pre>int id = reader.GetInt32(reader.GetOrdinal(&quot;Id&quot;));</pre><p><strong>GetString()</strong></p><ul><li>Reads a column as a string.</li><li>Edge case: Throws if the column is NULL. You’ll need to check with IsDBNull() first.</li></ul><pre>string name = reader.GetString(reader.GetOrdinal(&quot;Name&quot;));</pre><p><strong>GetBoolean()</strong></p><ul><li>Reads a column as a bool.</li><li>Edge case: Only works if the column is actually a bit/boolean type.</li></ul><pre>bool isActive = reader.GetBoolean(reader.GetOrdinal(&quot;IsActive&quot;));</pre><p><strong>GetDateTime()</strong></p><ul><li>Reads a column as a DateTime.</li><li>Edge case: Throws if the column is NULL or not a valid date.</li></ul><pre>DateTime created = reader.GetDateTime(reader.GetOrdinal(&quot;CreatedDate&quot;));</pre><p><strong>GetValue()</strong></p><ul><li>Returns the column as an object.</li><li>Edge case: Useful when you don’t know the type, but you’ll need to cast it later.</li></ul><pre>object emailObj = reader.GetValue(reader.GetOrdinal(&quot;Email&quot;));</pre><p><strong>GetFieldValue&lt;T&gt;</strong></p><ul><li>A generic method that lets you directly specify the type (reader.GetFieldValue&lt;string&gt;(ordinal)).</li><li>Edge case: Throws if the type doesn’t match.</li></ul><pre>string email = reader.GetFieldValue&lt;string&gt;(reader.GetOrdinal(&quot;Email&quot;));</pre><p><strong>IsDBNull()</strong></p><ul><li>Checks if a column is NULL.</li><li>Always use this before calling type-specific getters if the column might contain nulls.</li></ul><pre>var emailOrdinal = reader.GetOrdinal(&quot;Email&quot;);<br>string email = reader.IsDBNull(emailOrdinal) ? null : reader.GetString(emailOrdinal);</pre><p><strong>GetValue with NULL</strong></p><ul><li>Returns DBNull.Value if the column is NULL.</li><li>You can check for that and safely convert to null.</li></ul><pre>object emailObj = reader.GetValue(reader.GetOrdinal(&quot;Email&quot;));<br>string email = emailObj == DBNull.Value ? null : (string)emailObj;</pre><h3><strong>Mapping a DataReader to a C# Object</strong></h3><p>In real applications, we usually don’t want to return raw database columns throughout our application. Instead, we map the result into a C# object.</p><p>Suppose we have:</p><pre>public class Customer <br>{ <br>    public int Id { get; set; } <br>    public string Name { get; set; } <br>    public string Email { get; set; } <br>}</pre><p>We can map the reader:</p><pre>var customers = new List&lt;Customer&gt;();<br><br>while (await reader.ReadAsync()) {<br>  var customer = new Customer {<br>    Id = reader.GetInt32(reader.GetOrdinal(&quot;Id&quot;)), <br>    Name = reader.GetString(reader.GetOrdinal(&quot;Name&quot;)), <br>    Email = reader.GetString(reader.GetOrdinal(&quot;Email&quot;))<br>  };<br>  customers.Add(customer);<br>}</pre><p>Now the database representation has become a C# representation.</p><p>This mapping step is extremely important because it creates the boundary between your database and application domain.</p><h3>Reading a Single Value via ExecuteScalar( )</h3><p>Sometimes you don’t need an entire row. You might only need one value.</p><p>For example:</p><pre>SELECT COUNT(*) <br>FROM Customers;</pre><p>In this situation, using ExecuteReader would be unnecessary.</p><p>Instead the below will be more appropriate:</p><pre>await using var command = <br>    new SqlCommand( &quot;SELECT COUNT(*) FROM Customers&quot;, connection);<br><br>var result = await command.ExecuteScalarAsync();<br><br>var count = Convert.ToInt32(result);</pre><p>ExecuteScalar returns the first column of the first row in the result set.</p><h3>Using ExecuteNonQuery for Insert, Update and Delete Operations</h3><p>There are scenarios where SQL statement don’t return a result set.</p><p>For example:</p><pre>UPDATE Customers <br>SET Email = @Email <br>WHERE Id = @Id;</pre><p>We can execute this using:</p><pre>await using var command = new SqlCommand(<br>  &quot;&quot;&quot; <br>  UPDATE Customers <br>  SET Email = @Email <br>  WHERE Id = @Id <br>  &quot;&quot;&quot;, <br>  connection);<br><br>command.Parameters.Add(&quot;@Email&quot;, SqlDbType.NVarChar, 200)<br>    .Value = customer.Email;<br><br>command.Parameters.Add(&quot;@Id&quot;, SqlDbType.Int)<br>    .Value = customer.Id;<br><br>var rowsAffected = await command.ExecuteNonQueryAsync();</pre><p>The return value tells you how many rows were affected. For example, rowsAffected = 1</p><p>This is useful when determining whether an operation actually succeeded.</p><h3>Using SqlParameter Rather than Building with User Input</h3><p>Never do this:</p><pre>var sql =<br>    $&quot;SELECT * FROM Customers WHERE Email = &#39;{email}&#39;&quot;;</pre><p>When an application takes input from a user and directly inserts that input into a SQL statement, the user-controlled value can potentially change the meaning of the SQL query itself. This security vulnerability is known as <strong>SQL Injection</strong>.</p><p>At first glance, this looks harmless. If the user enters ben@example.com</p><p>The resulting SQL becomes:</p><pre>SELECT * <br>FROM Customers <br>WHERE Email = &#39;john@example.com&#39;</pre><p>The problem is that email is being treated as part of the SQL command itself.</p><p>An attacker could provide specially crafted input containing SQL syntax rather than simply providing an email address. For example, they might submit ‘ OR 1=1 — .</p><p>Because the input is concatenated directly into the SQL string, the resulting query could become:</p><pre>SELECT * <br>FROM Customers <br>WHERE Email = &#39;&#39; OR 1=1 --&#39;</pre><p>The OR 1=1 condition is always true, and -- comments out the remaining quote. As a result, the query may return every customer instead of only the customer matching a specific email address.</p><p>For example, imagine an application builds its query like this:</p><pre>var sql = <br>    $&quot;SELECT * FROM Customers WHERE Email = &#39;{email}&#39;&quot;;</pre><p>The application expects email to contain something like john@example.com</p><p>But because the value is being inserted directly into the SQL statement, SQL syntax supplied through the input can potentially escape the intended value and change the query.</p><h4>How Parameterization Prevents SQL Injection</h4><p>The solution is to use <strong>parameterized queries</strong>.</p><p>Instead of putting the user’s value directly into the SQL string, we create a parameter placeholder:</p><pre>var sql = &quot;&quot;&quot; <br>    SELECT Id, Name, Email <br>    FROM Customers <br>    WHERE Email = @Email <br>    &quot;&quot;&quot;;<br><br>await using var command = <br>    new SqlCommand(sql, connection);<br><br>command.Parameters.Add(<br>    &quot;@Email&quot;, <br>    SqlDbType.NVarChar, <br>    200).Value = email;</pre><p>The SQL statement contains WHERE Email = @Email while the actual value is supplied separately @Email = “john@example.com”</p><p>Conceptually, ADO.NET sends SQL Server two separate pieces of information.</p><p>SQL command:</p><pre>SELECT Id, Name, Email <br>FROM Customers <br>WHERE Email = @Email</pre><p>Parameter:</p><pre>@Email = &quot;john@example.com&quot;</pre><p>The important point is that the value supplied for @Email is treated as <strong>data</strong>, not as additional SQL syntax. So even if someone provides input containing characters or text that resemble SQL syntax, SQL Server receives that value as the value of the parameter rather than allowing it to become part of the SQL command structure.</p><h3>Add vs AddWithValue</h3><p>Most times, you will encounter:</p><pre>command.Parameters.AddWithValue(&quot;@Email&quot;, email);</pre><p>It works, but it is generally recommended to explicitly specify the SQL data type and size:</p><pre>command.Parameters.Add( &quot;@Email&quot;, SqlDbType.NVarChar, 200).Value = email;</pre><p>The reason is that explicit parameter metadata gives you greater control over the SQL type and avoids unwanted type inference.</p><p>For example:</p><pre>command.Parameters.Add( &quot;@CustomerId&quot;, SqlDbType.Int).Value = customerId;</pre><h3>Basic ADO.NET CRUD Operation</h3><p>At this point, we can summarize the four fundamental database operations.</p><p><strong>CREATE</strong></p><pre>await connection.OpenAsync(); <br><br>await using var command = new SqlCommand(&quot;&quot;&quot; INSERT INTO Customers (Name, Email) VALUES (@Name, @Email) &quot;&quot;&quot;, connection); <br><br>command.Parameters.Add(&quot;@Name&quot;, SqlDbType.NVarChar, 100).Value = customer.Name; <br><br>command.Parameters.Add(&quot;@Email&quot;, SqlDbType.NVarChar, 200).Value = customer.Email; <br>await command.ExecuteNonQueryAsync();</pre><p><strong>RETRIEVE</strong></p><pre>await connection.OpenAsync(); <br><br>await using var command = new SqlCommand(<br>&quot;SELECT Id, Name FROM Customers&quot;, connection<br>); <br><br>await using var reader = await command.ExecuteReaderAsync(); <br><br>while (await reader.ReadAsync()) <br>{ <br>    // Read row<br>}</pre><p><strong>UPDATE</strong></p><pre>await connection.OpenAsync(); <br><br>await using var command = new SqlCommand(&quot;&quot;&quot; UPDATE Customers SET Email = @Email WHERE Id = @Id &quot;&quot;&quot;, connection); <br><br>command.Parameters.Add(&quot;@Email&quot;, SqlDbType.NVarChar, 200).Value = customer.Email; <br><br>command.Parameters.Add(&quot;@Id&quot;, SqlDbType.Int).Value = customer.Id; <br><br>await command.ExecuteNonQueryAsync();</pre><p><strong>DELETE</strong></p><pre>await connection.OpenAsync(); <br><br>await using var command = new SqlCommand(&quot;&quot;&quot; DELETE FROM Customers WHERE Id = @Id &quot;&quot;&quot;, connection); <br><br>command.Parameters.Add(&quot;@Id&quot;, SqlDbType.Int).Value = customerId; <br>await command.ExecuteNonQueryAsync();</pre><h3>Stored Procedures with ADO.NET</h3><p>ADO.NET can execute SQL statements directly, but it can also execute stored procedures. Suppose SQL Server contains:</p><pre>CREATE PROCEDURE GetCustomerById<br>    @CustomerId INT<br>AS<br>BEGIN<br>    SELECT Id, Name, Email<br>    FROM Customers<br>    WHERE Id = @CustomerId;<br>END</pre><p>The C# code becomes:</p><pre>await using var command = new SqlCommand(<br>    &quot;GetCustomerById&quot;,<br>    connection);<br><br>command.CommandType = CommandType.StoredProcedure;<br><br>command.Parameters.Add(&quot;@CustomerId&quot;, SqlDbType.Int)<br>    .Value = customerId;<br><br>await using var reader = await command.ExecuteReaderAsync();<br><br>if (await reader.ReadAsync())<br>{<br>    var customer = new Customer<br>    {<br>        Id = reader.GetInt32(reader.GetOrdinal(&quot;Id&quot;)),<br>        Name = reader.GetString(reader.GetOrdinal(&quot;Name&quot;)),<br>        Email = reader.GetString(reader.GetOrdinal(&quot;Email&quot;))<br>    };<br>}</pre><p>The important line is:</p><pre>command.CommandType = CommandType.StoredProcedure;</pre><p>Without it, ADO.NET assumes that the command text is SQL.</p><h3>Transactions</h3><p>Transactions allow multiple database operations to be treated as one unit of work.</p><p>Consider a banking application where a customer transfers money from one account to another. The debit and credit operations should not be treated as two unrelated operations.</p><p>Suppose John wants to transfer ₦50,000 from Account 1 to Account 2. The database needs to perform two updates:</p><p>Dr Account 1 ₦50,000</p><p>Cr Account 2 ₦50,000</p><p>Both operations belong to one business transaction.</p><p>If the debit succeeds but the credit fails, the database would be left in an inconsistent state.</p><p>ADO.NET provides SqlTransaction for this purpose.</p><pre>await using var connection = new SqlConnection(connectionString); <br><br>await connection.OpenAsync(); <br><br>await using var transaction = await connection.BeginTransactionAsync(); <br>try <br>{ <br>    // Database operation 1 <br>    // Database operation 2 <br><br>    await transaction.CommitAsync(); <br>} <br>catch <br>{ <br>    await transaction.RollbackAsync(); <br>    throw; <br>}</pre><h3>DataTable and DataSet</h3><p>There is another approach in ADO.NET: disconnected data access using DataTable and DataSet. A DataTable represents tabular data in memory.</p><blockquote>Disconnected data access in ADO.NET means that your application can retrieve data from a database, store it in memory (using objects like DataTable or DataSet), and then work with that data without maintaining an active connection to the database. The downside is that since data is stored in memory, large datasets can consume significant resources.</blockquote><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*MQPuewCgzIn5R5grfFMUpQ.png" /></figure><p>A DataSet can contain multiple DataTable objects.</p><p>Previously, these classes were heavily used in applications that needed disconnected access to data.</p><pre>var table = new DataTable(); <br><br>await using var connection = new SqlConnection(connectionString); <br><br>await connection.OpenAsync(); <br><br>await using var command = new SqlCommand(<br>&quot;SELECT Id, Name, Email FROM Customers&quot;, connection<br>); <br><br>await using var reader = await command.ExecuteReaderAsync(); <br><br>table.Load(reader);</pre><p>You can then work with:</p><pre>foreach (DataRow row in table.Rows) <br>{ <br>  Console.WriteLine(row[&quot;Name&quot;]); <br>}</pre><h3>SqlDataReader vs DataTable</h3><p>With SqlDataReader:</p><p>SQL Server &gt; DataReader &gt; Read one row &gt; Read next row</p><p>With a DataTable:</p><p>SQL Server &gt; DataTable &gt; All required data held in memory</p><p>A reader is particularly useful for efficient sequential processing, especially with large result sets. A DataTable, on the other hand, provides an in-memory representation that can be accessed repeatedly after the database operation has completed.</p><p>For most modern API scenarios where the goal is to retrieve records and map them into application objects, SqlDataReader is often the more straightforward approach.</p><h3>Connection Pooling</h3><p>Connection pooling is a performance optimization technique that manages database connections efficiently. Instead of opening and closing a new physical connection to the database every time an application needs access, ADO.NET maintains a pool of reusable connections. When a request for a connection is made, the system checks the pool: if a suitable connection is available, it is returned; if not, a new one is created and added to the pool. Once the operation is complete, the connection is returned to the pool rather than being destroyed.</p><h3>How Connection Pooling Works</h3><ul><li>When you call Open() on a SqlConnection, ADO.NET checks if a matching connection already exists in the pool.</li><li>If available, it returns that connection instead of creating a new one.</li><li>When you call Close(), the connection is not destroyed but returned to the pool for reuse.</li><li>Pools are maintained per unique connection string and Windows identity.</li></ul><pre>  static void Main()<br>  {<br>      string connectionString =<br>          &quot;Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;&quot;;<br><br>      Stopwatch stopwatch = new Stopwatch();<br><br>      // First connection - pool creation<br>      stopwatch.Start();<br>      using (SqlConnection connection = new SqlConnection(connectionString))<br>      {<br>          connection.Open();<br>          Console.WriteLine(&quot;First connection opened.&quot;);<br>      }<br>      stopwatch.Stop();<br>      Console.WriteLine($&quot;Time taken: {stopwatch.ElapsedMilliseconds}ms\n&quot;);<br><br>      // Second connection - reused from pool<br>      stopwatch.Restart();<br>      using (SqlConnection connection = new SqlConnection(connectionString))<br>      {<br>          connection.Open();<br>          Console.WriteLine(&quot;Second connection opened.&quot;);<br>      }<br>      stopwatch.Stop();<br>      Console.WriteLine($&quot;Time taken: {stopwatch.ElapsedMilliseconds}ms&quot;);<br>  }<br></pre><h3>An End-to-End Request Flow</h3><p>Suppose a client sends: GET /api/accounts/1</p><ul><li>The request first reaches: AccountsController.GetById(1)</li><li>The controller calls: _service.GetAccountAsync(1);</li><li>The service calls: _repository.GetByIdAsync(1);</li><li>The repository creates: new SqlConnection(_connectionString)</li><li>It opens the connection: await connection.OpenAsync();</li><li>It then creates:</li></ul><pre>new SqlCommand( &quot;SELECT ... WHERE Id = @Id&quot;, connection);</pre><ul><li>The parameter is added: The parameter is added:</li><li>The command is executed: await command.ExecuteReaderAsync();</li><li>SQL Server executes the query and sends the result back.</li><li>The SqlDataReader reads the returned row.</li><li>The repository maps the database row into: Account</li><li>The account travels back through the service to the controller.</li><li>The controller returns: Ok(account) which causes ASP.NET Core to serialize the C# object into JSON, and send back to the client which may then display it in a presentable format to the user.</li></ul><h3>Practical Example: Internal Banking Application</h3><p>Imagine that we are building an internal banking API responsible for managing customer accounts.</p><p>An account contains information such as: Account Number, Customer Name, Balance, Created Date</p><p>The API will expose endpoints such as:</p><pre>GET /api/accounts <br>GET /api/accounts/{id} <br>POST /api/accounts <br>PUT /api/accounts/{id} <br>DELETE /api/accounts/{id} <br>POST /api/accounts/transfer</pre><p>Our architecture will look like this:</p><p>Client &gt; ASP .NET Core Api &gt; Controller &gt; Service &gt; Repository &gt; ADO .NET &gt; SQL Server</p><p>The above architecture is known as the <strong>Repository Pattern</strong>.</p><h4>Creating the Database</h4><p>In SQL Server, create a database called BankingDb.</p><pre>CREATE DATABASE BankingDb;</pre><p>Then create an Accounts table:</p><pre>USE BankingDb;<br><br>CREATE TABLE Accounts <br>( <br>    Id INT IDENTITY(1,1) PRIMARY KEY, <br>    AccountNumber NVARCHAR(20) NOT NULL UNIQUE, <br>    CustomerName NVARCHAR(150) NOT NULL, <br>    Balance DECIMAL(18,2) NOT NULL, <br>    CreatedAt DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME() <br>);</pre><p>We can proceed to insert some sample data:</p><pre>INSERT INTO Accounts (AccountNumber, CustomerName, Balance) <br>VALUES <br>(<br>&#39;10000001&#39;, &#39;John Smith&#39;, 250000.00<br>),<br>(<br>&#39;10000002&#39;, &#39;Jane Doe&#39;, 175000.00<br>);</pre><p>At this point, our database contains:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*fyzX5f6VdOqQ8s5RJwKsfw.png" /></figure><h4>Creating the ASP.NET Core Web API</h4><p>Create a new ASP.NET Core Web API project with the below structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Dy18FNzW1Hkt7owNuzpS-A.png" /></figure><p>The summary of the function of each folder/classes can be found below:</p><ul><li><strong>Controllers</strong> — Contains individual controllers that handle incoming HTTP requests and returns HTTP responses.</li><li><strong>AccountsController.cs</strong> — Defines API endpoints for account operations such as retrieving, creating, updating, and deleting accounts.</li><li><strong>Models</strong> — Contains C# classes that represent application data and API request structures.</li><li><strong>Account.cs</strong> — Represents an account retrieved from or stored in the database.</li><li><strong>CreateAccountRequest.cs</strong> — Defines the data required when creating a new account.</li><li><strong>TransferRequest.cs</strong> — Defines the data required to transfer money between two accounts.</li><li><strong>Repositories</strong> — Contains classes that handle direct communication with the database.</li><li><strong>IAccountRepository.cs</strong> — Defines the database operations that an account repository must provide.</li><li><strong>AccountRepository.cs</strong> — Implements the repository using ADO.NET to execute SQL against the database.</li><li><strong>Services</strong> — Contains business/application logic between controllers and repositories.</li><li><strong>AccountService.cs</strong> — Coordinates account operations and applies business rules before accessing the repository.</li><li><strong>appsettings.json</strong> — Stores application configuration such as the database connection string.</li><li><strong>Program.cs</strong> — Configures and starts the application, including dependency injection and services.</li></ul><blockquote>Note that your newly created Web API project will come with sample WeatherForecastController and WeatherForecast classes. You can opt to leave as is or delete both files.</blockquote><h4>Installing Microsoft.Data.SqlClient</h4><p>Previous .NET versions had ADO .NET functionality bundled in System.Data.SqlClient . However, that package is no longer actively supported by Microsoft. Rather, Microsoft.Data.SqlClient is the current supported package.</p><p>Proceed with installation by running the below command in your Command Prompt:</p><pre>dotnet add package Microsoft.Data.SqlClient</pre><p>Note that for the above command to run successfully, you should be in the same directory where your .csproj file is. Otherwise you may encounter the below error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FNXsDEBzeK3Z3fNuGUVx6g.png" /></figure><p>Alternatively, you can use the Package Manager Console:</p><pre>Install-Package Microsoft.Data.SqlClient</pre><p>You should get responses like this if installation is in progress:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*95YciHsXNPuEQch0Kljezg.png" /></figure><p>Confirm installation by checking your project’s .csproj file and ensuring the package is listed. Double-Click the project name at the right pane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L03_zKqDc2zwcXWn6o7I0g.png" /></figure><h4>Configuring the Connection String</h4><p>Add the database connection string to appsettings.json:</p><pre>{ <br>    &quot;ConnectionStrings&quot;: { <br>        &quot;DefaultConnection&quot;: &quot;Server=BENEDICT-IK\\SQLEXPRESS;<br>                              Database=BankingDb;<br>                              Trusted_Connection=True;<br>                              TrustServerCertificate=True&quot; <br>    } <br>}</pre><p>Note that server name can be found in your SQL Server instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*ledcHrhnGI0lINd-Dg_3mg.png" /></figure><p>For this demonstration, we are using <strong>Windows Authentication</strong>.</p><p>My appsettings now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vW3R9miMpacn1PqqufqSpQ.png" /></figure><h4>Creating the Account Model</h4><p>Create an Account class inside the Model folder.</p><pre>public class Account { <br>    public int Id { get; set; } <br>    public string AccountNumber { get; set; } <br>    public string CustomerName { get; set; } <br>    public decimal Balance { get; set; } <br>    public DateTime CreatedAt { get; set; } <br>}</pre><p>For creating an account, we will make use of Data Transfer Objects (DTOs) which will enable us hide properties we don’t want exposed to clients.</p><pre>public class CreateAccountRequest { <br>    public string AccountNumber { get; set; } <br>    public string CustomerName { get; set; } <br>    public decimal InitialBalance { get; set; } <br>}</pre><p>We do the same for transferring money:</p><pre>public class TransferRequest { <br>    public int SourceAccountId { get; set; } <br>    public int DestinationAccountId { get; set; } <br>    public decimal Amount { get; set; } <br>}</pre><p>Separating request models from the database model prevents the API contract from becoming tightly coupled to the database schema.</p><h4>Creating the Repository Interface</h4><p>The repository interface represents the data-access contract.</p><pre>public interface IAccountRepository { <br>    Task&lt;IEnumerable&lt;Account&gt;&gt; GetAllAsync(); <br>    Task&lt;Account?&gt; GetByIdAsync(int id); <br>    Task&lt;int&gt; CreateAsync(CreateAccountRequest request); <br>    Task&lt;bool&gt; UpdateAsync(int id, string customerName); <br>    Task&lt;bool&gt; DeleteAsync(int id); <br>    Task TransferAsync(int sourceAccountId, <br>    int destinationAccountId, decimal amount); <br>}</pre><h4>Implementing the Repository</h4><p>Now we can create the actual repository based on the defined interface.</p><pre>public class AccountRepository : IAccountRepository<br>{<br>    private readonly string _connectionString;<br>    public AccountRepository(IConfiguration configuration)<br>    {<br>        _connectionString = <br>            configuration.GetConnectionString(&quot;DefaultConnection&quot;)<br>            ?? throw new InvalidOperationException(&quot;Database connection string is missing.&quot;);<br>    }<br>    // Methods...<br>}</pre><p><strong>Retrieving All Accounts</strong></p><pre>public async Task&lt;IEnumerable&lt;Account&gt;&gt; GetAllAsync()<br>{<br>    var accounts = new List&lt;Account&gt;();<br><br>    const string sql = @&quot;<br>        SELECT Id, AccountNumber, CustomerName, Balance, CreatedAt<br>        FROM Accounts<br>        ORDER BY Id;&quot;;<br><br>    await using var connection = new SqlConnection(_connectionString);<br>    await connection.OpenAsync();<br><br>    await using var command = new SqlCommand(sql, connection);<br>    await using var reader = await command.ExecuteReaderAsync();<br><br>    while (await reader.ReadAsync())<br>    {<br>        var account = new Account<br>        {<br>            Id = reader.GetInt32(reader.GetOrdinal(&quot;Id&quot;)),<br>            AccountNumber = reader.GetString(reader.GetOrdinal(&quot;AccountNumber&quot;)),<br>            CustomerName = reader.GetString(reader.GetOrdinal(&quot;CustomerName&quot;)),<br>            Balance = reader.GetDecimal(reader.GetOrdinal(&quot;Balance&quot;)),<br>            CreatedAt = reader.GetDateTime(reader.GetOrdinal(&quot;CreatedAt&quot;))<br>        };<br><br>        accounts.Add(account);<br>    }<br><br>    return accounts;<br>}</pre><p><strong>Retrieving an Account by ID</strong></p><pre>public async Task&lt;Account?&gt; GetByIdAsync(int id)<br>{<br>    const string sql = @&quot;<br>        SELECT Id, AccountNumber, CustomerName, Balance, CreatedAt<br>        FROM Accounts<br>        WHERE Id = @Id;&quot;;<br><br>    await using var connection = new SqlConnection(_connectionString);<br>    await connection.OpenAsync();<br><br>    await using var command = new SqlCommand(sql, connection);<br>    command.Parameters.Add(&quot;@Id&quot;, SqlDbType.Int).Value = id;<br><br>    await using var reader = await command.ExecuteReaderAsync();<br><br>    if (!await reader.ReadAsync())<br>    {<br>        return null;<br>    }<br><br>    return new Account<br>    {<br>        Id = reader.GetInt32(reader.GetOrdinal(&quot;Id&quot;)),<br>        AccountNumber = reader.GetString(reader.GetOrdinal(&quot;AccountNumber&quot;)),<br>        CustomerName = reader.GetString(reader.GetOrdinal(&quot;CustomerName&quot;)),<br>        Balance = reader.GetDecimal(reader.GetOrdinal(&quot;Balance&quot;)),<br>        CreatedAt = reader.GetDateTime(reader.GetOrdinal(&quot;CreatedAt&quot;))<br>    };<br>}</pre><p>Important note:</p><p>In GetAllAsync(), when retrieving multiple records, we use:</p><pre>while (await reader.ReadAsync())</pre><p>However, for a simple record, we simply call:</p><pre>if (!await reader.ReadAsync())</pre><p>If it returns false, there was no matching record.</p><p><strong>Creating an Account</strong></p><pre>public async Task&lt;int&gt; CreateAsync(CreateAccountRequest request)<br>{<br>    const string sql = @&quot;<br>        INSERT INTO Accounts (AccountNumber, CustomerName, Balance)<br>        OUTPUT INSERTED.Id<br>        VALUES (@AccountNumber, @CustomerName, @Balance);&quot;;<br><br>    await using var connection = new SqlConnection(_connectionString);<br>    await connection.OpenAsync();<br><br>    await using var command = new SqlCommand(sql, connection);<br>    command.Parameters.Add(&quot;@AccountNumber&quot;, SqlDbType.NVarChar, 20).Value = request.AccountNumber;<br>    command.Parameters.Add(&quot;@CustomerName&quot;, SqlDbType.NVarChar, 150).Value = request.CustomerName;<br>    command.Parameters.Add(&quot;@Balance&quot;, SqlDbType.Decimal).Value = request.InitialBalance;<br><br>    var result = await command.ExecuteScalarAsync();<br>    return Convert.ToInt32(result);<br>}</pre><p>Note that in the script, OUTPUT INSERTED.Id returns the ID generated for the newly created account.</p><p><strong>Updating an Account</strong></p><pre>public async Task&lt;bool&gt; UpdateAsync(int id, string customerName)<br>{<br>    const string sql = @&quot;<br>        UPDATE Accounts<br>        SET CustomerName = @CustomerName<br>        WHERE Id = @Id;&quot;;<br><br>    await using var connection = new SqlConnection(_connectionString);<br>    await connection.OpenAsync();<br><br>    await using var command = new SqlCommand(sql, connection);<br>    command.Parameters.Add(&quot;@CustomerName&quot;, SqlDbType.NVarChar, 150).Value = customerName;<br>    command.Parameters.Add(&quot;@Id&quot;, SqlDbType.Int).Value = id;<br><br>    var rowsAffected = await command.ExecuteNonQueryAsync();<br>    return rowsAffected &gt; 0;<br>}</pre><p><strong>Deleting an Account</strong></p><pre>public async Task&lt;bool&gt; DeleteAsync(int id)<br>{<br>    const string sql = @&quot;<br>        DELETE FROM Accounts<br>        WHERE Id = @Id;&quot;;<br><br>    await using var connection = new SqlConnection(_connectionString);<br>    await connection.OpenAsync();<br><br>    await using var command = new SqlCommand(sql, connection);<br>    command.Parameters.Add(&quot;@Id&quot;, SqlDbType.Int).Value = id;<br><br>    var rowsAffected = await command.ExecuteNonQueryAsync();<br>    return rowsAffected &gt; 0;<br>}</pre><p><strong>TransferAsync</strong></p><pre>public async Task TransferAsync(<br>    int sourceAccountId,<br>    int destinationAccountId,<br>    decimal amount)<br>{<br>    await using var connection = new SqlConnection(_connectionString);<br>    await connection.OpenAsync();<br><br>    await using var transaction = (SqlTransaction)await connection.BeginTransactionAsync();<br><br>    try<br>    {<br>        const string debitSql = @&quot;<br>            UPDATE Accounts<br>            SET Balance = Balance - @Amount<br>            WHERE AccountNumber = @AccountId<br>              AND Balance &gt;= @Amount;&quot;;<br><br>        await using var debitCommand = new SqlCommand(debitSql, connection, transaction);<br>        debitCommand.Parameters.Add(&quot;@Amount&quot;, SqlDbType.Decimal).Value = amount;<br>        debitCommand.Parameters.Add(&quot;@AccountId&quot;, SqlDbType.Int).Value = sourceAccountId;<br><br>        var debitRows = await debitCommand.ExecuteNonQueryAsync();<br>        if (debitRows == 0)<br>        {<br>            throw new InvalidOperationException(&quot;Insufficient funds or source account does not exist.&quot;);<br>        }<br><br>        const string creditSql = @&quot;<br>            UPDATE Accounts<br>            SET Balance = Balance + @Amount<br>            WHERE AccountNumber = @AccountId;&quot;;<br><br>        await using var creditCommand = new SqlCommand(creditSql, connection, transaction);<br>        creditCommand.Parameters.Add(&quot;@Amount&quot;, SqlDbType.Decimal).Value = amount;<br>        creditCommand.Parameters.Add(&quot;@AccountId&quot;, SqlDbType.Int).Value = destinationAccountId;<br><br>        var creditRows = await creditCommand.ExecuteNonQueryAsync();<br>        if (creditRows == 0)<br>        {<br>            throw new InvalidOperationException(&quot;Destination account does not exist.&quot;);<br>        }<br><br>        await transaction.CommitAsync();<br>    }<br>    catch<br>    {<br>        await transaction.RollbackAsync();<br>        throw;<br>    }<br>}</pre><p>The full repository class thus becomes:</p><pre>public class AccountRepository : IAccountRepository<br>{<br>    private readonly string _connectionString;<br>    public AccountRepository(IConfiguration configuration)<br>    {<br>        _connectionString = configuration.GetConnectionString(&quot;DefaultConnection&quot;)<br>            ?? throw new InvalidOperationException(&quot;Database connection string is missing.&quot;);<br>    }<br>    // Methods...<br>    public async Task&lt;IEnumerable&lt;Account&gt;&gt; GetAllAsync()<br>    {<br>        var accounts = new List&lt;Account&gt;();<br><br>        const string sql = @&quot;<br>            SELECT Id, AccountNumber, CustomerName, Balance, CreatedAt<br>            FROM Accounts<br>            ORDER BY Id;&quot;;<br><br>        await using var connection = new SqlConnection(_connectionString);<br>        await connection.OpenAsync();<br><br>        await using var command = new SqlCommand(sql, connection);<br>        await using var reader = await command.ExecuteReaderAsync();<br><br>        while (await reader.ReadAsync())<br>        {<br>            var account = new Account<br>            {<br>                Id = reader.GetInt32(reader.GetOrdinal(&quot;Id&quot;)),<br>                AccountNumber = reader.GetString(reader.GetOrdinal(&quot;AccountNumber&quot;)),<br>                CustomerName = reader.GetString(reader.GetOrdinal(&quot;CustomerName&quot;)),<br>                Balance = reader.GetDecimal(reader.GetOrdinal(&quot;Balance&quot;)),<br>                CreatedAt = reader.GetDateTime(reader.GetOrdinal(&quot;CreatedAt&quot;))<br>            };<br><br>            accounts.Add(account);<br>        }<br><br>        return accounts;<br>    }<br><br>    public async Task&lt;Account?&gt; GetByIdAsync(int id)<br>    {<br>        const string sql = @&quot;<br>            SELECT Id, AccountNumber, CustomerName, Balance, CreatedAt<br>            FROM Accounts<br>            WHERE Id = @Id;&quot;;<br><br>        await using var connection = new SqlConnection(_connectionString);<br>        await connection.OpenAsync();<br><br>        await using var command = new SqlCommand(sql, connection);<br>        command.Parameters.Add(&quot;@Id&quot;, SqlDbType.Int).Value = id;<br><br>        await using var reader = await command.ExecuteReaderAsync();<br><br>        if (!await reader.ReadAsync())<br>        {<br>            return null;<br>        }<br><br>        return new Account<br>        {<br>            Id = reader.GetInt32(reader.GetOrdinal(&quot;Id&quot;)),<br>            AccountNumber = reader.GetString(reader.GetOrdinal(&quot;AccountNumber&quot;)),<br>            CustomerName = reader.GetString(reader.GetOrdinal(&quot;CustomerName&quot;)),<br>            Balance = reader.GetDecimal(reader.GetOrdinal(&quot;Balance&quot;)),<br>            CreatedAt = reader.GetDateTime(reader.GetOrdinal(&quot;CreatedAt&quot;))<br>        };<br>    }<br><br>    public async Task&lt;int&gt; CreateAsync(CreateAccountRequest request)<br>    {<br>        const string sql = @&quot;<br>            INSERT INTO Accounts (AccountNumber, CustomerName, Balance)<br>            OUTPUT INSERTED.Id<br>            VALUES (@AccountNumber, @CustomerName, @Balance);&quot;;<br><br>        await using var connection = new SqlConnection(_connectionString);<br>        await connection.OpenAsync();<br><br>        await using var command = new SqlCommand(sql, connection);<br>        command.Parameters.Add(&quot;@AccountNumber&quot;, SqlDbType.NVarChar, 20).Value = request.AccountNumber;<br>        command.Parameters.Add(&quot;@CustomerName&quot;, SqlDbType.NVarChar, 150).Value = request.CustomerName;<br>        command.Parameters.Add(&quot;@Balance&quot;, SqlDbType.Decimal).Value = request.InitialBalance;<br><br>        var result = await command.ExecuteScalarAsync();<br>        return Convert.ToInt32(result);<br>    }<br><br>    public async Task&lt;bool&gt; UpdateAsync(int id, string customerName)<br>    {<br>        const string sql = @&quot;<br>            UPDATE Accounts<br>            SET CustomerName = @CustomerName<br>            WHERE Id = @Id;&quot;;<br><br>        await using var connection = new SqlConnection(_connectionString);<br>        await connection.OpenAsync();<br><br>        await using var command = new SqlCommand(sql, connection);<br>        command.Parameters.Add(&quot;@CustomerName&quot;, SqlDbType.NVarChar, 150).Value = customerName;<br>        command.Parameters.Add(&quot;@Id&quot;, SqlDbType.Int).Value = id;<br><br>        var rowsAffected = await command.ExecuteNonQueryAsync();<br>        return rowsAffected &gt; 0;<br>    }<br><br>    public async Task&lt;bool&gt; DeleteAsync(int id)<br>    {<br>        const string sql = @&quot;<br>            DELETE FROM Accounts<br>            WHERE Id = @Id;&quot;;<br><br>        await using var connection = new SqlConnection(_connectionString);<br>        await connection.OpenAsync();<br><br>        await using var command = new SqlCommand(sql, connection);<br>        command.Parameters.Add(&quot;@Id&quot;, SqlDbType.Int).Value = id;<br><br>        var rowsAffected = await command.ExecuteNonQueryAsync();<br>        return rowsAffected &gt; 0;<br>    }<br><br>    public async Task TransferAsync(<br>        int sourceAccountId,<br>        int destinationAccountId,<br>        decimal amount)<br>    {<br>        await using var connection = new SqlConnection(_connectionString);<br>        await connection.OpenAsync();<br><br>        await using var transaction = (SqlTransaction)await connection.BeginTransactionAsync();<br><br>        try<br>        {<br>            const string debitSql = @&quot;<br>                UPDATE Accounts<br>                SET Balance = Balance - @Amount<br>                WHERE AccountNumber = @AccountId<br>                  AND Balance &gt;= @Amount;&quot;;<br><br>            await using var debitCommand = new SqlCommand(debitSql, connection, transaction);<br>            debitCommand.Parameters.Add(&quot;@Amount&quot;, SqlDbType.Decimal).Value = amount;<br>            debitCommand.Parameters.Add(&quot;@AccountId&quot;, SqlDbType.Int).Value = sourceAccountId;<br><br>            var debitRows = await debitCommand.ExecuteNonQueryAsync();<br>            if (debitRows == 0)<br>            {<br>                throw new InvalidOperationException(&quot;Insufficient funds or source account does not exist.&quot;);<br>            }<br><br>            const string creditSql = @&quot;<br>                UPDATE Accounts<br>                SET Balance = Balance + @Amount<br>                WHERE AccountNumber = @AccountId;&quot;;<br><br>            await using var creditCommand = new SqlCommand(creditSql, connection, transaction);<br>            creditCommand.Parameters.Add(&quot;@Amount&quot;, SqlDbType.Decimal).Value = amount;<br>            creditCommand.Parameters.Add(&quot;@AccountId&quot;, SqlDbType.Int).Value = destinationAccountId;<br><br>            var creditRows = await creditCommand.ExecuteNonQueryAsync();<br>            if (creditRows == 0)<br>            {<br>                throw new InvalidOperationException(&quot;Destination account does not exist.&quot;);<br>            }<br><br>            await transaction.CommitAsync();<br>        }<br>        catch<br>        {<br>            await transaction.RollbackAsync();<br>            throw;<br>        }<br>    }<br>}</pre><h4>Creating the Service Layer</h4><p>The repository is responsible for communicating with SQL Server while the service represents the application/business layer.</p><pre>public class AccountService<br>{<br>    private readonly IAccountRepository _repository;<br><br>    public AccountService(IAccountRepository repository)<br>    {<br>        _repository = repository ?? throw new System.ArgumentNullException(nameof(repository));<br>    }<br><br>    public Task&lt;IEnumerable&lt;Account&gt;&gt; GetAccountsAsync()<br>    {<br>        return _repository.GetAllAsync();<br>    }<br><br>    public Task&lt;Account?&gt; GetAccountAsync(int id)<br>    {<br>        return _repository.GetByIdAsync(id);<br>    }<br><br>    public Task&lt;int&gt; CreateAccountAsync(CreateAccountRequest request)<br>    {<br>        return _repository.CreateAsync(request);<br>    }<br><br>    public Task&lt;bool&gt; UpdateAccountAsync(int id, string customerName)<br>    {<br>        return _repository.UpdateAsync(id, customerName);<br>    }<br><br>    public Task&lt;bool&gt; DeleteAccountAsync(int id)<br>    {<br>        return _repository.DeleteAsync(id);<br>    }<br><br>    public Task TransferAsync(int sourceAccountId, int destinationAccountId, decimal amount)<br>    {<br>        return _repository.TransferAsync(sourceAccountId, destinationAccountId, amount);<br>    }<br>}</pre><h4><strong>Creating the Account Controller</strong></h4><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class AccountsController : ControllerBase<br>{<br>    private readonly AccountService _service;<br><br>    public AccountsController(AccountService service)<br>    {<br>        _service = service ?? throw new System.ArgumentNullException(nameof(service));<br>    }<br><br>    [HttpGet]<br>    public async Task&lt;IActionResult&gt; GetAll()<br>    {<br>        var accounts = await _service.GetAccountsAsync();<br>        return Ok(accounts);<br>    }<br><br>    [HttpGet(&quot;{id:int}&quot;)]<br>    public async Task&lt;IActionResult&gt; GetById(int id)<br>    {<br>        var account = await _service.GetAccountAsync(id);<br>        if (account is null)<br>        {<br>            return NotFound();<br>        }<br>        return Ok(account);<br>    }<br><br>    [HttpPost]<br>    public async Task&lt;IActionResult&gt; Create([FromBody] CreateAccountRequest request)<br>    {<br>        var id = await _service.CreateAccountAsync(request);<br>        return CreatedAtAction(nameof(GetById), new { id }, new { id });<br>    }<br><br>    [HttpPut(&quot;{id:int}&quot;)]<br>    public async Task&lt;IActionResult&gt; Update(int id, [FromBody] string customerName)<br>    {<br>        var updated = await _service.UpdateAccountAsync(id, customerName);<br>        if (!updated)<br>        {<br>            return NotFound();<br>        }<br>        return NoContent();<br>    }<br><br>    [HttpDelete(&quot;{id:int}&quot;)]<br>    public async Task&lt;IActionResult&gt; Delete(int id)<br>    {<br>        var deleted = await _service.DeleteAccountAsync(id);<br>        if (!deleted)<br>        {<br>            return NotFound();<br>        }<br>        return NoContent();<br>    }<br><br>    [HttpPost(&quot;transfer&quot;)]<br>    public async Task&lt;IActionResult&gt; Transfer(int sourceAccountId, int destinationAccountId, decimal amount)<br>    {<br>        await _service.TransferAsync(sourceAccountId, destinationAccountId, amount);<br>        return NoContent();<br>    }<br>}</pre><h4>Registering Dependencies in Program.cs</h4><p>We need to tell ASP.NET Core how to construct our services and repository.</p><p>In Program.cs, we add the below lines:</p><pre>builder.Services.AddScoped&lt;IAccountRepository, AccountRepository&gt;(); <br><br>builder.Services.AddScoped&lt;AccountService&gt;();</pre><p>My Program.cs file looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xkbqgUdlSXBIYTZQZ_7H2g.png" /></figure><h4>Install and Configure Swagger UI</h4><p>Starting with .NET 9, ASP.NET Core’s project templates no longer include Swashbuckle/Swagger UI by default. Instead, ASP.NET Core includes built-in OpenAPI document generation through Microsoft.AspNetCore.OpenApi. The generated OpenAPI document is not itself a graphical UI, so if you want the familiar interactive Swagger UI, you need to add a UI package separately.</p><p>From the terminal in your project folder, run the below command:</p><pre>dotnet add package Swashbuckle.AspNetCore.SwaggerUi</pre><p>Confirm installation by checking your project’s .csproj file and ensuring the package is listed. Double-Click the project name at the right pane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBHGLNeiHOfVm3pbK2kSHw.png" /></figure><p>Navigate to your Program.cs file and add the below line:</p><pre>    app.UseSwaggerUI(options =&gt;<br>    {<br>        options.SwaggerEndpoint(<br>            &quot;/openapi/v1.json&quot;,<br>            &quot;Banking API v1&quot;);<br>    });</pre><p>My Program.cs file now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPpCsoEvHkcqKNCrs3aHRQ.png" /></figure><h4>Run the Application</h4><p>Launch the application by pressing the play button at the top</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*boomn3FWVLB-vJnIH40vEg.png" /></figure><p>You should see the below screen. Ports may vary for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQKzvRjwPhec2_bhh2es_g.png" /></figure><ul><li><a href="https://localhost:7084/">https://localhost:7084</a> tells you where your app is running on https</li><li><a href="http://localhost:5238/">http://localhost:5238</a> tells you where your port is running on http.</li></ul><p>Run the <a href="https://localhost:7084/">https://localhost:7084</a> in a new tab, and add /swagger. Your URL should be something like: <a href="https://localhost:7084/swagger">https://localhost:7084/swagger</a></p><p>You should see the swagger UI display successfully</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-jz0zltrvEVlQxBuGbUsQ.png" /></figure><h4>Test the Application</h4><p>Expand <strong>GET /api/accounts </strong>&gt;<strong> </strong>Click <strong>Try it out</strong> &gt; <strong>Execute</strong></p><p>Your app should return a response of data earlier inserted in the db if successful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSoo6HzKypZX-ymSKjnfjw.png" /></figure><p>Do the same for other endpoints to confirm they work as expected.</p><p><strong>POST/api/accounts</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ePbXcmb1mwwRj9OTv8CTrg.png" /></figure><p>Verifying data in the database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*nnjhoLcrFhQi_swSdBVFkg.png" /></figure><p><strong>GET /api/accounts/{id}</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*36VUkeCXq-Ufe95p4xaMKA.png" /></figure><p><strong>PUT /api/accounts/{id}</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zoP2L-35xyoJNgAhkfzeag.png" /></figure><p>Note that it returns a status code of 204, which was stated in your controller, and simply means there is <strong>no content </strong>to return.</p><p>Verifying data in the database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*Q9PqMlxypVU2bY528gH5lQ.png" /></figure><p><strong>DELETE /api/accounts/{id}</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iNqb12-qeMK3ANzycqm5kg.png" /></figure><p>Verifying data in the database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*WXyHz3EwDOcQ7d-YCu_8Ag.png" /></figure><p>Note that in a standard enterprise environment, we don’t delete records. Instead, we use a flag such as <strong>isDeleted</strong> to determine whether record exists to the front end or not.</p><p><strong>POST /api/Accounts/transfer</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5uofs03s-KDerA3Hz5GROg.png" /></figure><p>Verifying data in the database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*rPRUwTArfxJppTQQJudXRw.png" /></figure><h3>Conclusion</h3><p>ADO.NET provides the fundamental building blocks for communicating with relational databases in .NET. By understanding SqlConnection, SqlCommand, SqlParameter, SqlDataReader, and transactions, you gain a clear picture of what happens between your application and the database.</p><p>In our practical example, we brought these concepts together in an ASP.NET Core Web API, following the flow from <strong>Controller → Service → Repository → ADO.NET → SQL Server</strong>. We also covered important practices such as parameterized queries, asynchronous database operations, proper resource management, and transactions.</p><p>You may eventually use higher-level tools such as Entity Framework Core or Dapper, but understanding ADO.NET gives you the foundation to understand what these abstractions are doing underneath the hood.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83bc783410f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Evolution of Program.cs File in .NET Applications]]></title>
            <link>https://benedictodoh.medium.com/the-evolution-of-program-cs-file-in-net-applications-2b2e5024c862?source=rss-771b70f7b31d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b2e5024c862</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Benedict Odoh]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 06:01:01 GMT</pubDate>
            <atom:updated>2026-08-24T06:01:01.264Z</atom:updated>
            <content:encoded><![CDATA[<p>In standard .NET applications, the <strong>Program.cs file</strong> has always been the entry point into the application. Over the years, its structure has evolved significantly, reflecting broader changes in the .NET ecosystem. In this article, we’ll explore how Program.cs has transformed across three major eras, <strong>pre-.NET 6</strong>, <strong>.NET 6</strong>, and <strong>.NET 7+. </strong>For this demonstration, let’s assume we are using a large ERP system that handles Finance, HR, and Inventory modules.</p><h3>Pre-.NET 6: The Startup.cs Era</h3><p>In older versions of .NET, Program.cs was ceremonial. It contained a <strong>Main </strong>method that bootstrapped the application and delegated all configuration to a <strong>Startup.cs</strong> class. This separation kept Program.cs lean but made the project verbose, especially in enterprise systems with dozens of services.</p><p><strong>Program.cs:</strong></p><pre>public class Program<br>{<br>    public static void Main(string[] args)<br>    {<br>        // 1. Create and run the application<br>        CreateHostBuilder(args).Build().Run();<br>    }<br><br>    public static IHostBuilder CreateHostBuilder(string[] args) =&gt;<br>         // 2. Create the default host<br>        Host.CreateDefaultBuilder(args)<br>            .ConfigureWebHostDefaults(webBuilder =&gt;<br>            {<br>                // 3. Use Startup to configure the application<br>                webBuilder.UseStartup&lt;Startup&gt;();<br>            });<br>}</pre><p><strong>Startup.cs:</strong></p><pre>public class Startup<br>{<br>    private readonly IConfiguration _config;<br><br>    public Startup(IConfiguration config)<br>    {<br>        _config = config;<br>    }<br><br>    // 4. Register application services<br>    public void ConfigureServices(IServiceCollection services)<br>    {<br>        services.AddControllers();<br>        services.AddDbContext&lt;FinanceDbContext&gt;();<br>        services.AddScoped&lt;IInvoiceService, InvoiceService&gt;();<br>        services.AddScoped&lt;IPaymentService, PaymentService&gt;();<br>    }<br><br>    // 5. Configure the HTTP request pipeline<br>    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)<br>    {<br>        if (env.IsDevelopment())<br>        {<br>            app.UseDeveloperExceptionPage();<br>        }<br><br>        app.UseHttpsRedirection();<br>        app.UseAuthentication();<br>        app.UseAuthorization();<br><br>        app.UseRouting();<br>        app.UseEndpoints(endpoints =&gt;<br>        {<br>            // 6. Map controller endpoints<br>            endpoints.MapControllers();<br>            endpoints.MapGet(&quot;/health&quot;, async ctx =&gt;<br>            {<br>                await ctx.Response.WriteAsync(&quot;ERP System Eunning...&quot;);<br>            });<br>        });<br>    }<br>}</pre><p>Here, Program.cs simply points to Startup.cs, which wires up services and middleware.</p><h3>.NET 6: Arrival of Top-Level Statements</h3><p>With .NET 6, the ceremony was stripped away. The Main method and Program class disappeared, replaced by <strong>top-level statements (TLS)</strong>. Service registration and middleware configuration moved directly into Program.cs.</p><p>This made bootstrapping faster but introduced a new problem: in large ERP systems, Program.cs quickly became bloated.</p><blockquote>A Top-Level Statement (TLS) is a feature that allows you to write code directly in the Program.cs file without explicitly wrapping it inside a Main method or a Program class. It’s essentially a shortcut that makes small applications, demos, and modern ASP.NET Core projects cleaner and easier to read. The compiler automatically generates the Main method behind the scenes.</blockquote><p><strong>Program.cs (with TLS):</strong></p><pre>// 1. Build application configuration<br>var builder = WebApplication.CreateBuilder(args);<br><br>// 2. Add services to the container<br>builder.Services.AddControllers();<br>builder.Services.AddDbContext&lt;FinanceDbContext&gt;();<br>builder.Services.AddScoped&lt;IInvoiceService, InvoiceService&gt;();<br><br>// 3. Configure an HTTP client for API calls<br>builder.Services.AddHttpClient(&quot;SAP&quot;, client =&gt;<br>{<br>    client.BaseAddress = new Uri(&quot;https://sap.api.company.com&quot;);<br>});<br><br>// 4. Build the application<br>var app = builder.Build();<br><br>// 5. Configure the HTTP request pipeline<br>app.UseHttpsRedirection();<br>app.UseAuthentication();<br>app.UseAuthorization();<br><br>// 6. Map controller endpoints<br>app.MapControllers();<br>// 7. Health check endpoint<br>app.MapGet(&quot;/health&quot;, () =&gt; &quot;ERP System OK&quot;);<br><br>// 8. Start the application<br>app.Run();</pre><h3>.NET 7+: Modular Extensions</h3><p>Modern .NET versions retain top-level statements but encourage <strong>modularization</strong>. Instead of wiring everything in Program.cs, our ERP system now encapsulates domain-specific services into <strong>extension classes</strong>. Program.cs becomes a thin orchestrator, while classes such as Finance, HR, and Inventory modules manage their own dependencies.</p><p><strong>Project Structure:</strong><br>ERPSystem/<br>├── Program.cs<br>├── Repositories/<br>│ ├── IInvoiceRepository.cs<br>│ ├── InvoiceRepository.cs<br>│ ├── IHRRepository.cs<br>│ ├── HRRepository.cs<br>│ ├── IInventoryRepository.cs<br>│ └── InventoryRepository.cs<br>├── Services/<br>│ ├── IInvoiceService.cs<br>│ ├── InvoiceService.cs<br>│ ├── IHRService.cs<br>│ ├── HRService.cs<br>│ ├── IInventoryService.cs<br>│ └── InventoryService.cs<br>├── Controllers/<br>│ ├── FinanceController.cs<br>│ ├── HRController.cs<br>│ └── InventoryController.cs<br>├── DbContexts/<br>│ ├── FinanceDbContext.cs<br>│ ├── HRDbContext.cs<br>│ └── InventoryDbContext.cs</p><p>Program.cs:</p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>// 1. Register modular ERP services<br>builder.Services.AddFinanceModule(builder.Configuration);<br>builder.Services.AddHRModule(builder.Configuration);<br>builder.Services.AddInventoryModule(builder.Configuration);<br><br>var app = builder.Build();<br><br>// 2. Configure the HTTP request pipeline<br>app.UseHttpsRedirection()<br>   .UseAuthentication()<br>   .UseAuthorization();<br><br>// 3. Map controller endpoints<br>app.MapControllers();<br>app.MapGet(&quot;/health&quot;, () =&gt; Results.Ok(&quot;ERP Healthy&quot;));<br><br>// 4. Start the application<br>app.Run();</pre><p><strong>FinanceModuleExtensions.cs:</strong></p><pre>public static class FinanceModuleExtensions<br>{<br>    // 5. Register Finance module services and configuration<br>    public static IServiceCollection AddFinanceModule(this IServiceCollection services, IConfiguration config)<br>    {<br>        // 6. Configure Finance database using SQL Server connection string<br>        services.AddDbContext&lt;FinanceDbContext&gt;(options =&gt;<br>            options.UseSqlServer(config.GetConnectionString(&quot;FinanceDb&quot;)));<br><br>        services.AddScoped&lt;IInvoiceService, InvoiceService&gt;();<br>        services.AddScoped&lt;IPaymentService, PaymentService&gt;();<br><br>        // 7. Register Finance controllers<br>        services.AddControllers(); <br><br>        return services;<br>    }<br>}</pre><p>Similar extension classes exist for HR and Inventory, each encapsulating their own DbContext, services, and controllers.</p><h3>Conclusion</h3><p>There goes the evolution of the master Program.cs class across various .NET versions. The idea is to embrace modularization and keep Program.cs as lean as possible. This approach not only makes Program.cs easier to maintain but also aligns with modern architectural best practices in large-scale systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b2e5024c862" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Not Your Regular Technical Post — Part 2]]></title>
            <link>https://benedictodoh.medium.com/not-your-regular-technical-post-part-2-23e2b4bd0f7c?source=rss-771b70f7b31d------2</link>
            <guid isPermaLink="false">https://medium.com/p/23e2b4bd0f7c</guid>
            <dc:creator><![CDATA[Benedict Odoh]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 05:27:38 GMT</pubDate>
            <atom:updated>2026-08-15T05:29:15.871Z</atom:updated>
            <content:encoded><![CDATA[<p>I remember the first time I came across an enterprise code. I was overwhelmed. I thought to myself, “What sort of Greek is this?” I didn’t know where to start from. Enterprise code involves many concepts you need to understand. Concepts like method overloading, method overriding, reflection, SOLID principles, and the likes. When starting out, unless you’re placed under a real conscious and renowned engineer who guides you, you will most likely have to figure things out yourself, and tbh, the development world is a fast-paced environment, and the likelihood of having that is closer to 0 than 1.</p><p>I recall a particular instance, I was shadowing a senior engineer, and we were dissecting how we would take on a project. He was like, he’d work on this service, and I’d work on that service. I remember looking up “what is a service” and “how can I implement one” on Google 😅. This was my first rodeo, and at that time, these were terms I wasn’t acquainted with. It’s laughable now, but it was a real dilemma then.</p><p>What helped, however, was that for every piece of code I didn’t understand or concepts I was struggling to grasp, I’d take note of it and do a read-up during my leisure time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*ucKTs6ouYGwKVSFUKoeNrw.png" /><figcaption>An excel sheet I kept to read up on concepts</figcaption></figure><p>Looking back, 20 months and a couple of deployed applications later, I can’t help but laugh at my naivety. The development world indeed has changed with the rise of AI tools, but understanding the fundamentals still helps to set you apart from the crowd.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23e2b4bd0f7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding C# Properties, Getters, Setters, and Backing Fields]]></title>
            <link>https://benedictodoh.medium.com/understanding-c-properties-getters-setters-and-backing-fields-37c821a095b6?source=rss-771b70f7b31d------2</link>
            <guid isPermaLink="false">https://medium.com/p/37c821a095b6</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[getters-and-setters]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Benedict Odoh]]></dc:creator>
            <pubDate>Sat, 25 Jul 2026 18:01:01 GMT</pubDate>
            <atom:updated>2026-07-27T19:17:28.473Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>One of the first things every .NET developer encounters is a model like this:</p><pre>public class User {<br>  public string FirstName {get; set; }<br>  public string LastName {get; set; }<br>  public int Age { get; set; }<br>}</pre><p>Most developers understand that this syntax “stores data” but few understand what actually happens under the hood.</p><p>Common questions a curious developer should ask include:</p><ul><li>What do get and set actually do?</li><li>Where is the value stored?</li><li>What is a backing field and what is its importance?</li><li>Why would someone write custom getters and setters instead of using { get; set; }?</li></ul><p>In this article, I will try to answer these questions the best I can.</p><h3>What is a Property?</h3><p>A property is a controlled way of exposing data from a class. Instead of exposing a variable directly, C# encourages exposing it through a property.</p><p>Instead of writing:</p><pre>public string Name;</pre><p>we usually write:</p><pre>public string Name { get; set; }</pre><p>Although they appear similar, they are fundamentally different.</p><p>A public <strong>field </strong>exposes the data directly, whereas a <strong>property </strong>acts as a gateway between external code and the underlying data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*J037Ske3l0xFVMc8QEozKA.png" /><figcaption>Properties with getters and setters</figcaption></figure><p>The property decides how data is retrieved and how data is stored.</p><h3>What Does get Do?</h3><p>The get accessor is used to retrieve the value of a property. When you call a property, the get block runs and returns the stored value. Think of it as a read-only operation; it lets you look at the data without changing it. For example, in an enterprise application, a Customer.Name property’s get would allow other parts of the system to read the customer’s name safely.</p><p>The property written manually looks like this:</p><pre>get {<br>    return _name;<br>  }</pre><p>When Customer.Name is read, the getter executes: return _name;</p><h3>What Does set Do?</h3><p>The set accessor is used to assign a new value to a property. When you give a property a value, the set block runs and updates the underlying field. This is the write operation.</p><p>For example:</p><pre>Customer.Name = &quot;Ben&quot;;</pre><p>Internally, this becomes:</p><pre>Name.set(&quot;John&quot;)</pre><p>Inside every setter is a special <strong>keyword </strong>named value.</p><pre>set {<br>  _name = value;<br>}</pre><p>During the assignment:</p><pre>Customer.Name = &quot;John&quot;;</pre><p>The keyword value equals &quot;John&quot;. The setter decides what should happen before the value is stored.</p><h3>Auto-Implemented Properties</h3><p>Auto-implemented properties in .NET are a shorthand way of writing properties without explicitly declaring a backing field. When you write something like:</p><pre>public string Name { get; set; }</pre><p>the compiler automatically creates a hidden private field behind the scenes to store the value.</p><p>Although they appear simple, the compiler secretly generates code similar to:</p><pre>public string Name {<br><br>  get {<br>    return _name;<br>  }<br>  set {<br>    _name = value;<br>  }<br><br>}</pre><h3>What Is a Backing Field?</h3><p>A backing field is the private variable that actually stores the property’s value. When you use get and set accessors, they interact with this backing field to retrieve or update the value.</p><pre>public class Customer<br>{<br>    private string _name;  // backing field<br><br>    public string Name<br>    {<br>        get { return _name; }   // retrieves value from backing field<br>        set { _name = value; }  // assigns value to backing field<br>    }<br>}</pre><p>The property itself does not store data. It merely controls access to the backing field.</p><h3>Why Use Your Own Backing Field?</h3><p>Auto-properties are perfect when no additional logic is required. However, real-world applications often need more than simply storing data. Custom backing fields are needed to:</p><ul><li>add <strong>validation</strong> in set.</li><li>add <strong>formatting or calculation</strong> in get.</li><li>maintain <strong>control</strong> over how data is stored and exposed.</li></ul><p>Take the below as an example:</p><pre>public class Customer<br>{<br>    // Simple auto-property for Name<br>    public string Name { get; set; }<br><br>    // Backing field for PurchaseDate<br>    private DateTime _purchaseDate;<br>    public string PurchaseDate<br>    {<br>        get { return _purchaseDate.ToString(&quot;yyyy-MM-dd&quot;); } // Formatting<br>        set <br>        {<br>            if (!DateTime.TryParse(value, out _purchaseDate))<br>                throw new ArgumentException(&quot;Invalid date format&quot;);<br>        }<br>    }<br><br>    // Backing field for Amount<br>    private decimal _amount;<br>    public decimal Amount<br>    {<br>        get { return _amount; }<br>        set <br>        {<br>            if (value &lt; 0) throw new ArgumentOutOfRangeException(&quot;Amount must be positive&quot;);<br>            _amount = value;<br>        }<br>    }<br>}</pre><p><strong>Name</strong>: Uses a default auto-property { get; set; } since no special logic is needed.</p><p><strong>PurchaseDate</strong>: Uses a backing field with a getter that formats the date as yyyy-MM-dd. The setter validates input by attempting to parse it into a DateTime.</p><p><strong>Amount</strong>: Uses a backing field with a setter that ensures the value is non-negative.</p><h3>Other Common Property Variations</h3><h4>Read-Only Property</h4><p>The value can be read but cannot be modified externally.</p><pre>public DateTime CreatedDate { get; }</pre><h4>Private Setter</h4><p>External code cannot change the ID. Only methods inside the class can. This is commonly used for database primary keys.</p><pre>public Guid Id { get; private set; }</pre><h4>Init-Only Property</h4><p>The value can be assigned only during object creation. After construction, it becomes immutable.</p><pre>public string Name { get; init; }</pre><h4>Sample Demonstration</h4><pre>public class Customer<br>{<br><br>    // Private setter for CustomerId<br>    public int CustomerId { get; private set; }<br><br>    // Auto-property for Name<br>    public string Name { get; set; }<br><br>    // Init-only property for Email (immutable after initialization)<br>    public string Email { get; init; }<br><br>    // Backing field for Amount<br>    private decimal _amount;<br>    public decimal Amount<br>    {<br>        get { return _amount; }<br>        set <br>        {<br>            if (value &lt; 0) throw new ArgumentOutOfRangeException(&quot;Amount must be positive&quot;);<br>            _amount = value;<br>        }<br>    }<br><br>    // Backing field for PurchaseDate<br>    private DateTime _purchaseDate;<br>    public string PurchaseDate<br>    {<br>        get { return _purchaseDate.ToString(&quot;yyyy-MM-dd&quot;); }<br>        set <br>        {<br>            if (!DateTime.TryParse(value, out _purchaseDate))<br>                throw new ArgumentException(&quot;Invalid date format&quot;);<br>        }<br>    }<br><br>    // Read-only property for computed value<br>    public decimal TotalPurchases =&gt; Amount * 1.05m; // Example: adds 5% tax<br>}</pre><ul><li><strong>Read-only property</strong>: TotalPurchases has only a get accessor. It’s computed dynamically based on Amount (here adding 5% tax). No setter is needed because it’s derived, not stored.</li><li><strong>Private setter</strong>: CustomerId can be read publicly but only set inside the class (e.g., in a constructor or factory method). This ensures external code cannot change IDs after creation.</li><li><strong>Init-only property</strong>: Email can only be set during object initialization. Once the object is constructed, the property becomes immutable, which is ideal for values that should never change.</li></ul><h3>How ASP.NET Core Uses Getters and Setters</h3><p>Understanding the ASP.NET Core request pipeline makes the role of properties much clearer.</p><h4>Request Model</h4><pre>public class CustomerRequest<br>{<br>    public string Name { get; set; }<br><br>    private DateTime _purchaseDate;<br>    public string PurchaseDate<br>    {<br>        get { return _purchaseDate.ToString(&quot;yyyy-MM-dd&quot;); }<br>        set<br>        {<br>            if (!DateTime.TryParse(value, out _purchaseDate))<br>                throw new ArgumentException(&quot;Invalid date format&quot;);<br>        }<br>    }<br><br>    private decimal _amount;<br>    public decimal Amount<br>    {<br>        get { return _amount; }<br>        set<br>        {<br>            if (value &lt; 0) throw new ArgumentOutOfRangeException(&quot;Amount must be positive&quot;);<br>            _amount = value;<br>        }<br>    }<br><br>    public decimal TotalPurchases =&gt; Amount * 1.05m; // read-only computed property<br>}</pre><h4>Example Client Request</h4><pre>{<br>  &quot;name&quot;: &quot;Alice&quot;,<br>  &quot;purchaseDate&quot;: &quot;2026-07-25&quot;,<br>  &quot;amount&quot;: 200<br>}</pre><h4>Step-by-Step Flow</h4><p><strong>Step 1: HTTP Request Arrives</strong></p><p>The browser sends an HTTP POST request containing JSON.</p><pre>POST /customers</pre><p><strong>Step 2 : Routing</strong></p><p>ASP.NET Core routing determines which controller action should handle the request.</p><pre>[HttpPost]<br>public IActionResult Create(CustomerRequest request)</pre><p><strong>Step 3: Model Binding Creates the Object</strong></p><p>The framework first creates an empty instance:</p><pre>CustomerRequest request = new CustomerRequest();</pre><p>Initially:</p><ul><li>Name = null</li><li>PurchaseDate = null</li><li>Amount = 0</li></ul><p><strong>Step 4: JSON Deserialization</strong></p><p>The JSON body is read property by property. For each property, the <strong>setter</strong> is called:</p><pre>request.Name = &quot;Alice&quot;;          // calls set { Name = value; }<br>request.PurchaseDate = &quot;2026-07-25&quot;; // setter validates and stores backing field<br>request.Amount = 200;            // setter validates non-negative</pre><p>Every property is populated through its setter. The framework does not bypass your property logic.</p><p><strong>Step 5: Model Validation</strong></p><p>If attributes like [Required], [Range], or [StringLength] are present, ASP.NET Core validates the populated model. If validation fails, ModelState becomes invalid before the controller action executes.</p><p><strong>Step 6: Controller Execution</strong></p><p>Now the controller receives a fully populated object:</p><pre>public IActionResult Create(CustomerRequest request)<br>{<br>    Console.WriteLine(request.Name); // calls getter<br>}</pre><p>Reading request.Name calls the <strong>getter</strong>.</p><p><strong>Step 7: Service Layer</strong></p><p>The controller usually forwards the model to a service:</p><pre>_customerService.Create(request);</pre><p>Whenever the service reads a property, the <strong>getter</strong> executes. Whenever it assigns a property on another object, that object’s <strong>setter</strong> executes.</p><p><strong>Step 8: Entity Framework Core</strong></p><p>Suppose the service creates an entity:</p><pre>var customer = new Customer<br>{<br>    Name = request.Name,<br>    PurchaseDate = request.PurchaseDate,<br>    Amount = request.Amount<br>};<br><br>_context.Customers.Add(customer);<br>await _context.SaveChangesAsync();</pre><ul><li>During SaveChangesAsync(), EF Core reads the entity’s property values (via getters) to build the SQL INSERT.</li><li>When EF Core materializes entities from the database, it populates them through configured properties or backing fields.</li></ul><h3>Conclusion</h3><p>Understanding getters, setters, and backing fields provides a solid foundation for understanding model binding, validation, Entity Framework Core, serialization, and encapsulation. Once these concepts are clear, the behavior of ASP.NET Core applications, from receiving an HTTP request to persisting data in a database, becomes much easier to understand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37c821a095b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preventing Sleep Mode: Keeping ASP.NET Core Background Services Alive with Scheduled Tasks]]></title>
            <link>https://benedictodoh.medium.com/preventing-sleep-mode-keeping-asp-net-core-background-services-alive-with-scheduled-tasks-068b44e99824?source=rss-771b70f7b31d------2</link>
            <guid isPermaLink="false">https://medium.com/p/068b44e99824</guid>
            <dc:creator><![CDATA[Benedict Odoh]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 18:01:01 GMT</pubDate>
            <atom:updated>2026-06-17T18:01:01.069Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nfbjz9EKlyOo4smeUPyDwQ.png" /></figure><h3>Background</h3><p>I recently worked on a project involving a background service designed to consume multiple APIs. Its primary role was to act as a polling service, fetching data at configured intervals for internal applications. The initial implementation was an ASP.NET Core Web Application hosted on IIS, with several BackgroundService classes responsible for periodically calling upstream APIs, processing the responses, and storing results for downstream use. Everything ran flawlessly during local testing. However, once deployed to IIS, an unusual issue emerged: the workers would run as expected for a while, making API calls at their scheduled intervals, but then they would seemingly “go to sleep.” No further calls were made until the application was manually refreshed via a web browser or the IIS application pool was recycled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*OiajHIhELxCXGlyRbK-_gg.png" /></figure><p>The first assumption was that the issue was related to the worker implementation itself. Extensive logging was introduced to track worker startup, execution cycles, HTTP requests, responses, exceptions, and scheduled delays. The logs confirmed that the workers were successfully completing their tasks and entering their delay periods as expected. However, after some time, the logs would stop completely, indicating that the process hosting the workers was no longer running.</p><p>Attention then shifted to IIS configuration. Since ASP.NET Core background services hosted within IIS are tied to the lifecycle of the IIS worker process, it was suspected that IIS was unloading or recycling the application. Several IIS settings were reviewed and adjusted. The Application Pool’s <strong>Start Mode</strong> was changed to <strong>AlwaysRunning</strong> to ensure the application pool remained active even during periods of inactivity. The <strong>Idle Time-out</strong> was set to <strong>0</strong> to disable idle shutdown, while the <strong>Idle Time-out Action</strong> remained configured to terminate the process if an idle timeout ever occurred. The <strong>Regular Time Interval (Recycle)</strong> was also set to <strong>0</strong> to prevent periodic application pool recycles, and no specific recycle times were configured. Additionally, <strong>Application Initialization</strong> and <strong>Preload Enabled</strong> settings were reviewed to ensure the application could automatically start without requiring a user request.</p><p>To further mitigate the issue, a keep-alive mechanism was introduced. A dedicated worker periodically invoked an internal endpoint within the application to simulate traffic and prevent IIS from considering the application idle. This was intended to keep the application pool active and ensure the hosted background services continued executing. Despite these measures, the issue persisted, indicating that inactivity alone was not the root cause.</p><p>The next phase of troubleshooting focused on identifying whether IIS or ASP.NET Core was intentionally shutting down the application. Application lifetime logging was added using IHostApplicationLifetime to capture ApplicationStarted, ApplicationStopping, and ApplicationStopped events. This proved to be extremely valuable because it confirmed that the application was not crashing; rather, it was receiving graceful shutdown notifications. The logs clearly showed the application entering the stopping and stopped states, which suggested that an external process was instructing IIS to terminate the application.</p><p>The server’s Event Viewer was then examined in detail. Application logs revealed repeated <strong>IIS AspNetCore Module V2 Event ID 1033</strong> entries indicating that multiple applications were being shut down. Importantly, this was not isolated to the worker application alone. Other unrelated applications hosted on the same server, including applications running in different application pools, were also experiencing shutdown events. This finding significantly changed the direction of the investigation because it demonstrated that the problem was not caused by the worker code, background services, or HTTP client implementation.</p><p>Further analysis of IIS event providers pointed to APPHOSTSVC (Application Host Helper Service) activity in the CFGHISTORY directories. These entries suggested configuration changes were occurring, since IIS creates snapshots whenever applicationHost.config or related files are updated. The timing of these events aligned with the shutdowns, raising the possibility that configuration updates, maintenance tasks, deployments, security software, or other server-level processes were triggering restarts.</p><p>The difference was that other applications shut down would immediately spring back to life the moment an incoming request hit their endpoints. Mine didn’t. Like Newton’s First Law of Motion, it would remain in its state of rest until acted upon by an external force. In practical terms, that external force was me manually reloading the application URL in a browser. While this was manageable in the test environment, it was not a realistic approach for production. I couldn’t expect support staff to remember to periodically browse a URL just to keep a polling service alive. The solution needed to be automatic, reliable, and simple enough to deploy quickly.</p><p>Throughout the investigation, several potential causes were systematically ruled out. The workers themselves were functioning correctly, HTTP requests were completing successfully, no unhandled exceptions were being observed, and the application pools had been configured to remain active indefinitely. The evidence increasingly pointed toward infrastructure-level events occurring outside the application. In other words, the workers were not “sleeping” due to a coding defect; they were being terminated because the hosting environment was shutting down the application process.</p><p>One of the options suggested throughout my research was to completely redesign the solution as a dedicated .NET Worker Service running as a Windows Service. From a technical standpoint, it made sense. Worker Services are purpose-built for long-running background processing and are not tied to the lifecycle of IIS. However, I was reluctant to take that route because within my team, background processes were traditionally hosted inside Web API or ASP.NET Core applications. A dedicated Windows Service would represent a significant deviation from the established pattern. More importantly, I work in an environment that operates under a zero-trust policy. Introducing a completely new deployment architecture would require multiple approvals, reviews, and justifications. With production deadlines looming, I wasn’t eager to start a lengthy governance process for what was essentially a background polling application.</p><p>Fortunately, while exploring alternative approaches, I stumbled upon a surprisingly simple solution: <strong>Windows Task Scheduler</strong>.</p><h3>The Antidote</h3><p>The idea was straightforward. If the application only needed an external trigger to wake it up whenever it was shut down, then why not automate that trigger? Using Task Scheduler, I created a scheduled task that periodically invoked a lightweight endpoint exposed by the application. In effect, this acted as a heartbeat mechanism or hot-reload trigger. Whenever the hosting process became dormant or was unloaded due to environmental factors, the scheduled task would make an HTTP request to the application, causing it to start up again and resume execution of its background services.</p><p>What I particularly liked about this solution was that it required no architectural redesign, no additional infrastructure, and no major deployment changes. It worked entirely within the constraints of the existing environment. The background services remained embedded within the web application, while the scheduled task provided a lightweight safety net that ensured the application would not remain dormant indefinitely.</p><p>Below is a detailed guide on how I set it up:</p><p>1) Log into the server housing the services and create a folder in a writable path. Preferably, it should be the same folder that houses your worker log.</p><p>2) Inside that folder, create a sub-folder named “PSLogs”. From my perspective, the current directory becomes: “C:\ABCWorkerService\PSLogs”</p><p>3) Inside the PSLogs create a workercheck PowerShell and Visual Basic script e.g., workercheck.ps1 and workercheck.vbs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4679h4q_3knZTrnqc9yJiA.png" /></figure><p>4) Open the workercheck.vbs and modify:</p><pre>Set objShell = CreateObject(&quot;Wscript.Shell&quot;)<br>objShell.Run &quot;powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\ABCWorkerService\PSLogs\workercheck.ps1&quot;, 0, True</pre><p>Basically, I am pointing to the PowerShell script and executing via WScript. This lets me automate execution silently in the background with no console window flickering.</p><p>5) Open the workercheck.ps1 and modify:</p><pre># Base folder for logs<br>$logDir   = &quot;C:\ABCWorkerService\PSLogs&quot;<br>$baseName = &quot;ABCTaskSchedulerLog&quot;<br>$maxSizeMB = 5   # rollover threshold<br><br># Build today&#39;s log file name with prefix<br>$today    = Get-Date -Format &#39;yyyyMMdd&#39;<br>$logPath = Join-Path $logDir ($baseName + &quot;_&quot; + $today + &quot;.txt&quot;)<br><br>function Write-Log($message) {<br>    $timestamp = Get-Date -Format &#39;yyyy-MM-dd HH:mm:ss&#39;<br>    $entry     = &quot;$timestamp - $message&quot;<br><br>    # Check if log exists and exceeds size<br>    if (Test-Path $logPath) {<br>        $sizeMB = (Get-Item $logPath).Length / 1MB<br>        if ($sizeMB -ge $maxSizeMB) {<br>            $archivePath = &quot;$logPath.$(Get-Date -Format &#39;HHmmss&#39;).bak&quot;<br>            Move-Item $logPath $archivePath -Force<br>        }<br>    }<br><br>    $entry | Out-File $logPath -Append<br>}<br><br>try {<br>    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12<br>    # Point to the bg service URL<br>    $response = Invoke-WebRequest -Uri &quot;https://jsonplaceholder.typicode.com/posts/1&quot; -TimeoutSec 15 -UseBasicParsing<br>    Write-Log &quot;Status: $($response.StatusCode) $($response.StatusDescription) - Content: $($response.Content)&quot;<br>}<br>catch {<br>    Write-Log &quot;ERROR: $($_.Exception.Message)&quot;<br>}</pre><p>Note that for this demonstration, I decided to utilize the free JSONPlaceholder API. You are to replace the URI here with that of your background service.</p><p>6) Open the PowerShell console in admin mode and execute the below script, section by section, i.e., Create Action &gt; Create triggers &gt; Create settings &gt; Register Task</p><pre># Action<br>$action = New-ScheduledTaskAction `<br>    -Execute &quot;wscript.exe&quot; `<br>    -Argument &quot;C:\ABCWorkerService\PSLogs\workercheck.vbs&quot;<br><br># Daily trigger at 6 AM until midnight<br>$triggerDaily = New-ScheduledTaskTrigger -Daily -At &quot;06:00&quot;<br><br># Build repetition object for daily cycle<br>$repetition = (New-ScheduledTaskTrigger -Once -At &quot;06:00&quot; `<br>                  -RepetitionInterval (New-TimeSpan -Minutes 5) `<br>                  -RepetitionDuration (New-TimeSpan -Hours 18)).Repetition<br><br>$triggerDaily.Repetition = $repetition<br><br># Startup trigger<br>$triggerStartup = New-ScheduledTaskTrigger -AtStartup<br><br># Settings<br>$settings = New-ScheduledTaskSettingsSet `<br>  -ExecutionTimeLimit (New-TimeSpan -Minutes 1) `<br>  -RestartCount 3 `<br>  -RestartInterval (New-TimeSpan -Minutes 1) `<br>  -AllowStartIfOnBatteries `<br>  -DontStopIfGoingOnBatteries<br><br># Register the task with SYSTEM account<br>Register-ScheduledTask `<br>  -TaskName &quot;AutoStart_ABCWorkerService&quot; `<br>  -Action $action `<br>  -Trigger @($triggerDaily, $triggerStartup) `<br>  -Settings $settings `<br>  -RunLevel Highest `<br>  -User &quot;SYSTEM&quot; `<br>  -Force</pre><p>This script registers a scheduled task called <strong>AutoStart_ABCWorkerService</strong> that runs the VBScript (workercheck.vbs) using wscript.exe. It is configured to start automatically at system startup and also every day at 6:00 AM, repeating every 5 minutes until midnight. The task runs under the <strong>SYSTEM</strong> account with the highest privileges, ignores battery/AC restrictions, and has safeguards like a 1‑minute execution time limit and automatic retries if it fails.</p><p>Once done, you should see an output showing you the TaskPath, TaskName, and its State.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k65MkilNWKRxlH46e-wl7Q.png" /></figure><p>7) Open Task Scheduler UI and click on the “Task Scheduler Library” on the left-hand side. You should see your newly created task in the list displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHL4peJoFXQkijQrvCerSw.png" /></figure><p>At this point, your task is already set up.</p><p>8) Once the above have been established, test the task by hitting “Run” on the right-hand side. Wait for about 10s or so and hit “Refresh”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3kak-CF2DyXSUyDt_nVLbQ.png" /></figure><p>9) Slide the horizontal scroll to the right and examine the “Last Run Result” column. A successful run will always have a (0x0) code attached.</p><p>10) Review the logs in the PSLogs sub-folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5VrkdAO02sx5GNNr_NDUng.png" /></figure><p>From the logs, you can get success and error messages that can guide your debugging process. If you encounter failures, common causes could be the background service itself being down, in which case you should review the worker logs for deeper troubleshooting, or network connectivity problems that prevent the script from reaching its target. By analyzing these log entries, you can quickly narrow down the root issue and take the appropriate corrective steps. A sample of both instances can be found below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KTAryYaqPy3SP3wQKUdnvQ.png" /></figure><h3>Conclusion</h3><p>In essence, the solution was not about preventing the application from shutting down; it was about guaranteeing that it would automatically recover whenever it did. Sometimes the best solution is not the most sophisticated one, but the one that balances technical correctness, operational realities, and organizational constraints.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=068b44e99824" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>