Whenever I look at how online shopping platforms manage discounts, one thing becomes clear: displaying a coupon code is only a small part of the process. Behind every working coupon, there is a system responsible for generating codes, checking their validity, managing expiration dates, tracking usage, and calculating discounts.

For developers, building such a system is an interesting way to understand how different parts of an application work together.

In this article, I will walk through how I would build a basic coupon management system using ASP.NET Core and Entity Framework Core. My goal is to keep the implementation practical and explain the important decisions behind the code.

I will use an e-commerce scenario where customers can apply discount codes during checkout. The same approach can also be adapted for coupon platforms such as RabattDigga, where managing different offers, discount codes, and their validity is an important part of the overall experience.

1. Planning the Coupon Management System

Before writing code, I would first identify what the application needs to handle.

A basic coupon management system should support:

  • Creating and updating coupon codes.
  • Defining fixed or percentage-based discounts.
  • Setting minimum order amounts.
  • Managing coupon start and expiration dates.
  • Limiting the number of times a coupon can be redeemed.
  • Preventing customers from using the same coupon repeatedly.
  • Calculating discounts during checkout.

I would divide the application into three main parts:

  1. API Layer: Handles incoming requests from the client.
  2. Business Logic Layer: Validates coupons and calculates discounts.
  3. Data Access Layer: Uses Entity Framework Core to communicate with SQL Server.

This separation makes the application easier to maintain and extend.

2. Creating the ASP.NET Core Project

I would start by creating an ASP.NET Core Web API project.

Using the .NET CLI:

Bash
dotnet new webapi -n CouponManagement
cd CouponManagement

Next, I would install the Entity Framework Core packages required for SQL Server.

Bash
dotnet add package Microsoft.EntityFrameworkCore.SqlServer

dotnet add package Microsoft.EntityFrameworkCore.Tools

Entity Framework Core allows me to work with database records through C# objects instead of writing SQL queries for every operation.

3. Designing the Coupon Entity

The first important step is designing the database structure.

I would create a Coupon entity containing the information required to manage each discount code.

C#
public class Coupon
{
    public int Id { get; set; }

    public string Code { get; set; } = string.Empty;

    public decimal DiscountValue { get; set; }

    public string DiscountType { get; set; } = "Percentage";

    public decimal MinimumOrderAmount { get; set; }

    public DateTime StartDate { get; set; }

    public DateTime ExpiryDate { get; set; }

    public int MaxRedemptions { get; set; }

    public int RedeemedCount { get; set; }

    public bool IsActive { get; set; }
}

I would also create a separate entity to track coupon redemptions.

C#
public class CouponRedemption
{
    public int Id { get; set; }

    public int CouponId { get; set; }

    public string UserId { get; set; } = string.Empty;

    public DateTime RedeemedAt { get; set; }

    public decimal DiscountApplied { get; set; }

    public Coupon? Coupon { get; set; }
}

Keeping redemption records separate is important. It allows me to track which customer used a particular coupon and how much discount was applied.

It also makes reporting easier when I want to understand which coupons are performing well.

4. Configuring Entity Framework Core

Now I need to connect these entities to the database.

I would create a CouponDbContext class.

C#
using Microsoft.EntityFrameworkCore;

public class CouponDbContext : DbContext
{
    public CouponDbContext(
        DbContextOptions<CouponDbContext> options)
        : base(options)
    {
    }

    public DbSet<Coupon> Coupons => Set<Coupon>();

    public DbSet<CouponRedemption> CouponRedemptions
        => Set<CouponRedemption>();

    protected override void OnModelCreating(
        ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Coupon>()
            .HasIndex(c => c.Code)
            .IsUnique();

        modelBuilder.Entity<CouponRedemption>()
            .HasIndex(r => new { r.CouponId, r.UserId })
            .IsUnique();

        modelBuilder.Entity<CouponRedemption>()
            .HasOne(r => r.Coupon)
            .WithMany()
            .HasForeignKey(r => r.CouponId);
    }
}

There are two important database constraints here.

First, every coupon code must be unique. Second, the same user should not be able to redeem the same coupon more than once.

I prefer enforcing these rules at the database level as well as in the application logic. This provides additional protection when multiple requests are processed simultaneously.

5. Connecting the SQL Server Database

I would store the database connection string in appsettings.json.

JSON
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=CouponDB;Trusted_Connection=True;TrustServerCertificate=True"
  }
}

Then I would register the database context in Program.cs.

C#
builder.Services.AddDbContext<CouponDbContext>(
    options =>
        options.UseSqlServer(
            builder.Configuration.GetConnectionString(
                "DefaultConnection")));

For a production application, I would use secure configuration or environment variables for database credentials rather than exposing sensitive connection details in source control.

After configuring the connection, I would create the database migration.

Bash
dotnet ef migrations add InitialCreate
dotnet ef database update

At this point, the database structure is ready.

6. Building the Coupon Validation Logic

This is where the main business logic comes in.

I would never allow a coupon to be applied simply because its code exists in the database. The application must check several conditions before accepting it.

For example:

  • Is the coupon active?
  • Has its validity period started?
  • Has it expired?
  • Has it reached its redemption limit?
  • Does the customer's order meet the minimum amount?
  • Has the customer already redeemed it?

I would put these checks inside a dedicated service rather than placing all the logic inside an API controller.

Here is a simplified validation method:

C#
public async Task<Coupon?> ValidateCouponAsync(
    string code,
    decimal orderAmount)
{
    var normalizedCode = code.Trim().ToUpperInvariant();

    var coupon = await _context.Coupons
        .FirstOrDefaultAsync(c => c.Code == normalizedCode);

    if (coupon == null || !coupon.IsActive)
        return null;

    var now = DateTime.UtcNow;

    if (now < coupon.StartDate || now > coupon.ExpiryDate)
        return null;

    if (coupon.RedeemedCount >= coupon.MaxRedemptions)
        return null;

    if (orderAmount < coupon.MinimumOrderAmount)
        return null;

    return coupon;
}

I would normalize coupon codes before searching so that differences in letter casing do not create unnecessary validation problems.

I would also store and compare dates consistently in UTC to avoid timezone-related issues.

7. Calculating the Discount Amount

Once the coupon passes validation, the next step is calculating the discount.

I would support two common discount types:

  • Percentage discount.
  • Fixed amount discount.

Here is a simple calculation method:

C#
public decimal CalculateDiscount(
    Coupon coupon,
    decimal orderAmount)
{
    decimal discount = 0;

    if (coupon.DiscountType == "Percentage")
    {
        discount = orderAmount *
                   (coupon.DiscountValue / 100);
    }
    else if (coupon.DiscountType == "Fixed")
    {
        discount = coupon.DiscountValue;
    }

    return Math.Min(
        Math.Max(discount, 0),
        orderAmount);
}

For example, if a customer has a €100 order and applies a 20% coupon, the discount would be €20.

For a fixed €10 coupon, the customer would receive a €10 discount.

I use Math.Min to ensure that the discount never exceeds the order amount.

In a production system, I would also validate discount values when coupons are created and apply the appropriate currency rounding rules.

8. Preventing Multiple Redemptions

One issue I would pay particular attention to is duplicate coupon redemption.

Imagine a coupon has only one remaining use. Two customers attempt to redeem it at almost exactly the same time.

If the application simply reads the current redemption count and then updates it, both requests might pass validation.

To avoid this, I would use a database transaction and an atomic conditional update.

For example:

C#
using var transaction =
    await _context.Database.BeginTransactionAsync();

var updated = await _context.Coupons
    .Where(c => c.Id == coupon.Id &&
                c.RedeemedCount < c.MaxRedemptions)
    .ExecuteUpdateAsync(setters =>
        setters.SetProperty(
            c => c.RedeemedCount,
            c => c.RedeemedCount + 1));

if (updated == 0)
{
    await transaction.RollbackAsync();
    return false;
}

_context.CouponRedemptions.Add(
    new CouponRedemption
    {
        CouponId = coupon.Id,
        UserId = userId,
        RedeemedAt = DateTime.UtcNow,
        DiscountApplied = discount
    });

await _context.SaveChangesAsync();

await transaction.CommitAsync();

return true;

The conditional update ensures that the redemption count increases only when the coupon still has available uses.

The unique database index on CouponId and UserId provides another layer of protection against duplicate redemptions.

If a database constraint fails, I would handle the exception and roll back the transaction.

This is especially important for coupon systems that may receive a large number of checkout requests during seasonal shopping events.

9. Exposing the Coupon Functionality Through an API

Once the business logic is ready, I would expose it through an ASP.NET Core API.

For example, a customer could submit a coupon code and order amount using an HTTP POST request.

A simple request model might look like this:

C#
public class ApplyCouponRequest
{
    public string Code { get; set; } = string.Empty;

    public decimal OrderAmount { get; set; }
}

I would then create an API endpoint that receives the request and calls the coupon service.

C#
[ApiController]
[Route("api/[controller]")]
public class CouponsController : ControllerBase
{
    private readonly ICouponService _couponService;

    public CouponsController(
        ICouponService couponService)
    {
        _couponService = couponService;
    }

    [HttpPost("validate")]
    public async Task<IActionResult> Validate(
        ApplyCouponRequest request)
    {
        var coupon = await _couponService.ValidateCouponAsync(
            request.Code,
            request.OrderAmount);

        if (coupon == null)
        {
            return BadRequest(new
            {
                Message = "Invalid or expired coupon."
            });
        }

        var discount = _couponService.CalculateDiscount(
            coupon,
            request.OrderAmount);

        return Ok(new
        {
            CouponCode = coupon.Code,
            DiscountAmount = discount,
            FinalAmount = request.OrderAmount - discount
        });
    }
}

I would register the service through dependency injection in Program.cs.

The example focuses on coupon validation and preview. Actual redemption should happen as part of a trusted checkout process after the order and customer have been verified. I would never trust a client-submitted user ID or order amount without server-side verification.

10. Testing the Coupon Management System

Before considering the application ready, I would test different scenarios.

Test scenario

Expected result

Valid coupon

Coupon accepted

Expired coupon

Coupon rejected

Inactive coupon

Coupon rejected

Minimum order not reached

Coupon rejected

Redemption limit reached

Coupon rejected

Duplicate user redemption

Coupon rejected

Valid percentage discount

Correct discount calculated

Valid fixed discount

Correct discount calculated

I would also test concurrent redemption requests to make sure that the coupon usage limit cannot be exceeded.

For this, I would use automated tests with a real SQL Server test database rather than relying only on in-memory database testing for transaction and concurrency behavior.

11. What I Would Improve in a Production Application

The implementation above provides a foundation, but I would not stop there if I were building a coupon system for a production e-commerce platform.

There are several improvements I would consider:

Role-Based Access Control: Only authorized administrators should be able to create, edit, or deactivate coupons.

Coupon Categories: Allow coupons to apply to specific products, brands, or shopping categories.

Advanced Usage Limits: Support per-user limits, campaign-level limits, and different redemption rules.

Audit Logging: Record who created or modified a coupon and when changes occurred.

API Security: Implement authentication, authorization, input validation, and rate limiting.

Caching: Cache frequently requested coupon information where appropriate, while ensuring that redemption limits and availability are always checked against authoritative database state.

Monitoring: Track failed validations, redemption attempts, and API response times to identify problems.

These improvements would help turn a basic coupon application into a more reliable system.

Conclusion

Building a coupon management system is a useful practical exercise because it brings together several important concepts in modern .NET development.

Through ASP.NET Core, I can expose the functionality through APIs. Entity Framework Core makes database operations easier to manage, while SQL Server provides the structure needed to store coupons and redemption records.

The most important part, in my opinion, is not simply generating discount codes. It is making sure that every coupon follows the correct rules, that customers receive accurate discounts, and that redemption limits remain consistent even when multiple requests arrive simultaneously.

Whether I am developing a small e-commerce application or working with a larger coupon platform, these principles provide a solid starting point for building a reliable coupon management system.

I would continue improving the application as business requirements grow, but keeping the database structure, validation rules, and redemption logic well organized from the beginning makes future development much easier.