LESSON 1 OF 18

1. Project Setup, Architecture, and SQL Server Infrastructure

Create a .NET 10 ASP.NET Core Web API, establish a feature-based structure, configure SQL Server and EF Core, and prepare the initial e-commerce entities.

100 dk 102

Introduction

A professional REST API is more than a collection of endpoints. A reliable API also needs a clear project structure, a correctly configured data-access layer, consistent naming conventions, and a domain model that can evolve without creating unnecessary coupling. In this first lesson, we will prepare the foundation for the sample e-commerce API used throughout the course.

The application will contain products, categories, customers, and orders. In later lessons, we will build REST endpoints and add DTOs, validation, centralized error handling, pagination, filtering, Swagger, security, and performance improvements. For that reason, we will make deliberate decisions about file organization, configuration, and entity design from the beginning.

The goal of this lesson is not to build a complete e-commerce system. The goal is to create a maintainable foundation on which the remaining lessons can safely build.

1. Project goals and technical decisions

We will create a project named Store.Api. The technology stack is C#, .NET 10, ASP.NET Core Web API, Entity Framework Core 10, and SQL Server. We will use controller-based APIs so that HTTP contracts, routes, and response behavior remain explicit and easy to inspect.

Two common organizational approaches are:

  • Layered architecture: API, Application, Domain, and Infrastructure are separated into layers.
  • Feature-based organization: Product, Category, Customer, and Order code is grouped by business capability.

For this course, we will begin with a feature-based structure inside a single Web API project. This reduces unnecessary project complexity for a small or medium-sized application. As the system grows, the same boundaries can be moved into separate Application and Infrastructure projects. The important rule is to organize code around responsibility and business behavior.

2. Create the ASP.NET Core Web API project

Open a terminal, move to your working directory, and run:

dotnet new webapi --use-controllers -n Store.Api -f net10.0 cd Store.Api dotnet restore

The --use-controllers option selects the controller-based Web API template. The -f net10.0 option targets .NET 10. The template may contain sample weather files. We will remove those later and replace them with our own domain model.

Build and run the initial project:

dotnet build dotnet run

While the application is running, open the HTTPS address displayed in the terminal or call it with an HTTP client. At this stage, the purpose is simply to confirm that the SDK, project template, and development certificate work correctly.

3. Establish the folder structure

For the first version, use the following structure:

Store.Api/ ├── Controllers/ ├── Data/ ├── Features/ │   ├── Categories/ │   ├── Customers/ │   ├── Orders/ │   └── Products/ ├── Models/ ├── Migrations/ ├── Properties/ ├── appsettings.json ├── appsettings.Development.json └── Program.cs

The Data folder contains the database context and data-access configuration. The Models folder contains entity classes used as the persistence model. The Features folder will later keep controllers, DTOs, validation, and query logic close to the related business capability.

Organizing a file by business feature instead of only by technical type improves navigation. For example, product request DTOs and product controllers can live under Features/Products rather than being scattered across distant folders.

4. Add EF Core and SQL Server packages

Add the SQL Server provider and the design package used by migration tooling:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer dotnet add package Microsoft.EntityFrameworkCore.Design

Use EF Core packages compatible with the target framework and with one another. EF Core providers generally do not work across major versions. In a .NET 10 application, allow the package manager to resolve EF Core 10 packages or explicitly standardize the versions for your team.

5. Design the domain entities

We will start with the core entities. At this stage, entities represent the foundation of database tables and relationships. Later, we will use DTOs for API requests and responses so that the persistence model is not exposed directly as the public client contract.

Category and Product

namespace Store.Api.Models; public class Category {    public int Id { get; set; }    public string Name { get; set; } = string.Empty;    public ICollection<Product> Products { get; set; } = new List<Product>(); } public class Product {    public int Id { get; set; }    public string Name { get; set; } = string.Empty;    public string Description { get; set; } = string.Empty;    public decimal Price { get; set; }    public int StockQuantity { get; set; }    public bool IsActive { get; set; } = true;    public int CategoryId { get; set; }    public Category? Category { get; set; } }

Product and Category form a many-to-one relationship. One category can contain many products, while each product points to one category. decimal is more appropriate than double for monetary values. Currency, rounding, and database precision rules will be discussed in greater detail later.

Customer, Order, and OrderItem

namespace Store.Api.Models; public class Customer {    public int Id { get; set; }    public string FirstName { get; set; } = string.Empty;    public string LastName { get; set; } = string.Empty;    public string Email { get; set; } = string.Empty;    public ICollection<Order> Orders { get; set; } = new List<Order>(); } public class Order {    public int Id { get; set; }    public DateTime CreatedAtUtc { get; set; } = DateTime.UtcNow;    public string Status { get; set; } = "Pending";    public int CustomerId { get; set; }    public Customer? Customer { get; set; }    public ICollection<OrderItem> Items { get; set; } = new List<OrderItem>(); } public class OrderItem {    public int Id { get; set; }    public int Quantity { get; set; }    public decimal UnitPrice { get; set; }    public int OrderId { get; set; }    public Order? Order { get; set; }    public int ProductId { get; set; }    public Product? Product { get; set; } }

OrderItem resolves the many-to-many relationship between orders and products. Storing the purchase-time product price in UnitPrice is essential. If the current product price changes later, the historical order total must not change.

6. Create the DbContext

Create Data/ApplicationDbContext.cs:

using Microsoft.EntityFrameworkCore; using Store.Api.Models; namespace Store.Api.Data; public class ApplicationDbContext : DbContext {    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)        : base(options)    {    }    public DbSet<Product> Products => Set<Product>();    public DbSet<Category> Categories => Set<Category>();    public DbSet<Customer> Customers => Set<Customer>();    public DbSet<Order> Orders => Set<Order>();    public DbSet<OrderItem> OrderItems => Set<OrderItem>();    protected override void OnModelCreating(ModelBuilder modelBuilder)    {        modelBuilder.Entity<Product>()            .Property(product => product.Price)            .HasPrecision(18, 2);        modelBuilder.Entity<OrderItem>()            .Property(item => item.UnitPrice)            .HasPrecision(18, 2);        modelBuilder.Entity<Customer>()            .HasIndex(customer => customer.Email)            .IsUnique();    } }

The DbContext represents the unit of work between the entities and the database. Each DbSet is an entry point for querying and changing a particular entity type. The OnModelCreating method is used for rules that cannot be inferred from the C# classes or that should be explicitly documented.

7. Configure the connection string and dependency injection

Add a development connection string to appsettings.json:

{  "ConnectionStrings": {    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=StoreDb;Trusted_Connection=True;TrustServerCertificate=True;MultipleActiveResultSets=true"  } }

Never place production passwords or secrets in source control. Use User Secrets, environment variables, or a secure secret manager. The example above is intended for local development with LocalDB. If you use SQL Server in a container or on another host, adjust the server, authentication, and security options for that environment.

Register the context in Program.cs:

using Microsoft.EntityFrameworkCore; using Store.Api.Data; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddOpenApi(); var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")    ?? throw new InvalidOperationException(        "Connection string 'DefaultConnection' was not found."); builder.Services.AddDbContext<ApplicationDbContext>(options =>    options.UseSqlServer(connectionString)); var app = builder.Build(); if (app.Environment.IsDevelopment()) {    app.MapOpenApi(); } app.UseHttpsRedirection(); app.MapControllers(); app.Run();

AddDbContext registers the context with a scoped lifetime by default. In a web application, one HTTP request commonly represents one unit of work, so this lifetime is an appropriate default. Registering a DbContext as a singleton can create state-management and concurrent-use problems because DbContext is not thread-safe.

8. Create the first migration and database

Create a migration and apply it to SQL Server:

dotnet ef migrations add InitialCreate dotnet ef database update

The first command converts model changes into migration files. The second applies those migrations to the database. Keep the Migrations folder in source control; migration files represent the history of the database schema.

If the EF command is not available, install the CLI tool:

dotnet tool install --global dotnet-ef

If the migration command cannot find the connection string, check the key name, JSON syntax, active environment, and configuration files. The application may run successfully while the design-time command reads a different configuration source.

9. Verify the first database

Use SQL Server Object Explorer, SQL Server Management Studio, or another SQL client to confirm that the database was created. The following tables should exist:

TablePurpose
CategoriesStores product categories.
ProductsStores product data and its category relationship.
CustomersStores customer information.
OrdersStores the order header, customer relationship, and status.
OrderItemsStores products, quantities, and purchase-time prices for orders.

We have not created controllers yet, so data cannot be submitted over HTTP. This is intentional. Establishing the infrastructure before designing the public API contract gives us a more controlled starting point.

Common mistakes

  • Hard-coding connection strings: Environment-specific values should come from the configuration system.
  • Returning entities directly from API endpoints: This can expose internal fields and create navigation-property cycles. DTOs will solve this later.
  • Registering DbContext as a singleton: A scoped lifetime is the normal choice for request-oriented web applications.
  • Using double for money: Floating-point rounding can produce incorrect financial results; use decimal instead.
  • Deleting migration files: This removes part of the shared schema history and complicates team development.
  • Using local time: Different servers and clients may use different time zones. Store timestamps in UTC and convert them at the presentation boundary.

Short practice exercise

Complete the following exercise locally:

  1. Create the Store.Api project targeting .NET 10.
  2. Add the SQL Server provider and EF Core Design packages.
  3. Create the five entities shown in this lesson.
  4. Implement ApplicationDbContext with relationships and decimal precision rules.
  5. Add the connection string and register the context with dependency injection.
  6. Create the InitialCreate migration and update the database.
  7. Confirm that the unique customer email index and product price precision appear in the generated migration.

Conclusion

In this lesson, we created the shared foundation for the course project. We started a .NET 10 controller-based Web API, selected a feature-based organization, added the SQL Server provider, defined the initial entities, and configured EF Core through dependency injection. We also practiced reading connection strings from configuration, creating migrations, and expressing important database rules.

In the next stage, we will build professional endpoints by applying the concepts of resources and representations. The most important lesson from this setup is that API quality begins before the first endpoint is written: project boundaries, data modeling, configuration, and team conventions should be intentional from day one.

Sources