LESSON 4 OF 16

4. SQL Server Database and Entity Framework Core Modeling

This lesson designs relational tables in SQL Server and maps primary keys, foreign keys, and relationships to Entity Framework Core entity classes.

75 dk 87

Introduction

In the previous lesson, we created domain models, DTOs, and data contracts. This lesson connects those concepts to a relational database design in SQL Server. The goal is not simply to create a few classes, but to make deliberate decisions about how data is stored, how tables are related, and how Entity Framework Core understands those relationships.

Our example application is a product catalog. Each Category can contain multiple Product records, while each product belongs to one category. In SQL Server this is a one-to-many relationship; in .NET it is represented through a foreign key and navigation properties.

The examples assume .NET 8, C# 12, Entity Framework Core 8, and SQL Server 2022. Most of the concepts remain applicable to later EF Core versions.

Relational Database Foundations

Tables, rows, and columns

In a relational database, each table represents a particular type of data. The Categories table stores categories, and the Products table stores products. Rows represent individual records, while columns represent their attributes.

TableExample columnsPurpose
CategoriesCategoryId, NameStore product categories
ProductsProductId, Name, Price, CategoryIdStore product information

Primary keys

A primary key uniquely identifies every row in a table. A numeric int key or a Guid is commonly used. In this example, CategoryId and ProductId are primary keys. A primary key cannot contain duplicate or NULL values.

Foreign keys

A foreign key connects a row in one table to a row in another table. Products.CategoryId references Categories.CategoryId. This allows the database to prevent a product from referencing a category that does not exist.

The table containing the principal key is called the principal; the table containing the foreign key is the dependent. In this example, Category is the principal entity and Product is the dependent entity.

Preparing Entity Classes

Entity classes represent domain objects that are persisted in the database. DTOs belong to the API contract, whereas entities belong to the persistence and domain model. Keeping these responsibilities separate prevents accidental exposure of database details.

namespace Catalog.Domain.Entities;

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; } = string.Empty;

    public ICollection<Product> Products { get; set; } = new List<Product>();
}

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; } = string.Empty;
    public decimal Price { get; set; }
    public bool IsActive { get; set; }

    public int CategoryId { get; set; }
    public Category Category { get; set; } = null!;
}

EF Core can recognize CategoryId and ProductId as primary keys by convention. Product.CategoryId is the foreign key property. The Category and Products navigation properties provide an object-oriented way to work with the relationship.

Because CategoryId is non-nullable, the relationship is required: every product must have a category. If a product could exist without a category, the foreign key would be declared as int?.

Designing the SQL Server Schema

Before creating migrations, it is useful to understand the database schema that the model represents. Migration commands will be covered in the next lesson.

CREATE TABLE Categories
(
    CategoryId INT IDENTITY(1,1) NOT NULL,
    Name NVARCHAR(100) NOT NULL,
    CONSTRAINT PK_Categories PRIMARY KEY (CategoryId),
    CONSTRAINT UQ_Categories_Name UNIQUE (Name)
);

CREATE TABLE Products
(
    ProductId INT IDENTITY(1,1) NOT NULL,
    Name NVARCHAR(200) NOT NULL,
    Price DECIMAL(18,2) NOT NULL,
    IsActive BIT NOT NULL,
    CategoryId INT NOT NULL,
    CONSTRAINT PK_Products PRIMARY KEY (ProductId),
    CONSTRAINT FK_Products_Categories_CategoryId
        FOREIGN KEY (CategoryId) REFERENCES Categories(CategoryId)
);

IDENTITY allows SQL Server to generate numeric key values when rows are inserted. NVARCHAR supports Unicode text. For monetary values, decimal provides predictable precision compared with floating-point types. DECIMAL(18,2) means 18 total digits with 2 digits after the decimal separator.

The NOT NULL constraint on Products.CategoryId makes the relationship mandatory. The behavior when a category is deleted must also be selected deliberately. The operation may be restricted when products exist, or dependent products may be deleted with the category. This is a business and data-integrity decision, not merely an ORM setting.

Mapping with the Fluent API

EF Core can build a model using conventions. However, explicit configuration is preferable for important choices such as table names, string lengths, decimal precision, relationships, and delete behavior.

using Catalog.Domain.Entities;
using Microsoft.EntityFrameworkCore;

namespace Catalog.Infrastructure.Persistence;

public class CatalogDbContext : DbContext
{
    public DbSet<Category> Categories => Set<Category>();
    public DbSet<Product> Products => Set<Product>();

    public CatalogDbContext(DbContextOptions<CatalogDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Category>(entity =>
        {
            entity.ToTable("Categories");
            entity.HasKey(x => x.CategoryId);

            entity.Property(x => x.Name)
                .HasMaxLength(100)
                .IsRequired();

            entity.HasIndex(x => x.Name)
                .IsUnique();
        });

        modelBuilder.Entity<Product>(entity =>
        {
            entity.ToTable("Products");
            entity.HasKey(x => x.ProductId);

            entity.Property(x => x.Name)
                .HasMaxLength(200)
                .IsRequired();

            entity.Property(x => x.Price)
                .HasPrecision(18, 2);

            entity.Property(x => x.IsActive)
                .IsRequired();

            entity.HasOne(x => x.Category)
                .WithMany(x => x.Products)
                .HasForeignKey(x => x.CategoryId)
                .OnDelete(DeleteBehavior.Restrict);
        });
    }
}

HasOne states that a product has one category, while WithMany states that a category has many products. HasForeignKey identifies the key on the dependent side. DeleteBehavior.Restrict prevents a category containing products from being deleted automatically. This example favors protection against accidental data loss.

Data Annotations versus Fluent API

Another option is to configure the model with attributes such as [Key], [Required], [MaxLength], and [ForeignKey].

public class Product
{
    [Key]
    public int ProductId { get; set; }

    [Required, MaxLength(200)]
    public string Name { get; set; } = string.Empty;

    [Column(TypeName = "decimal(18,2)")]
    public decimal Price { get; set; }

    public int CategoryId { get; set; }

    [ForeignKey(nameof(CategoryId))]
    public Category Category { get; set; } = null!;
}

Data annotations are convenient for simple rules, but they can fill domain classes with database-specific details. Fluent API keeps persistence configuration in the infrastructure layer and provides greater control for complex relationships. In this course, we keep entity classes focused and prefer Fluent API configuration.

Modeling Checklist

  • Give every persistent entity a clear and unique primary key.
  • Ensure the foreign key type matches the principal key type.
  • Represent required and optional relationships correctly with nullable types.
  • Set reasonable maximum lengths for string properties.
  • Use suitable precision and scale for monetary and measurement values.
  • Use a unique index or constraint when a value must be unique.
  • Choose delete behavior after considering data-loss scenarios.

Common Mistakes

Using DTOs as entities

Mapping an incoming API DTO directly to a database entity can allow clients to change fields they should not control. For example, clients should not normally provide the database-generated product identifier or audit fields.

Omitting the foreign key property

EF Core may discover a relationship from navigation properties alone, but an explicit CategoryId makes filtering, validation, and updates easier to understand and test.

Leaving string lengths unlimited

Unbounded strings can result in unexpected SQL Server column types or unnecessarily large columns. A domain-appropriate limit improves both data quality and database design.

Using cascade delete everywhere

Cascade delete may look convenient, but deleting one category could silently remove thousands of products. Deletion behavior should be designed as part of the business rules.

Practice Exercise

Extend the model with a supplier relationship:

  1. Create a Supplier entity with SupplierId, Name, and Email properties.
  2. Model a relationship in which one supplier can have many products, while a product may optionally have a supplier.
  3. Add nullable int? SupplierId and a nullable Supplier navigation property to Product.
  4. Limit the supplier name to 150 characters and design an appropriate index for the email field.
  5. Explain why a unique constraint is useful when attempting to add the same category name twice.

Review question: Why should SupplierId be int? rather than int? The answer depends on the business rule that a product may exist without a supplier.

Conclusion

This lesson demonstrated how SQL Server tables and Entity Framework Core entity models express the same data contract. Primary keys uniquely identify records, foreign keys preserve relational integrity, and navigation properties make relationships accessible in .NET code.

In the next lesson, we will connect CatalogDbContext to the application configuration, define the connection string, and use migrations to transfer model changes to SQL Server. The modeling decisions made here form the foundation of the data access layer that follows.

Sources