LESSON 6 OF 20

6. Designing the Data Model with Entity Framework Core

Learn how to model categories, articles, authors, and tags as relational entities for a practical content management system using EF Core.

55 dk 37

Introduction

In the previous lessons, we completed form design and validation. We can now begin designing the persistent data layer of our application. In a content management system, creating only an Article class is not enough. We must also model which category contains the article, which author wrote it, and which tags are associated with it.

In this lesson, we will create Entity Framework Core entity classes for our ASP.NET Core MVC project. We will define one-to-many and many-to-many relationships, then use the Fluent API to configure table and column rules. At the end of the lesson, we will have a consistent model that is ready for migrations.

Planning the data model

Let us translate the CMS requirements into a relational design:

  • A Category can contain many articles.
  • An Article belongs to one category.
  • An Author can write many articles.
  • An Article belongs to one author.
  • An article can have multiple tags.
  • A tag can be used by multiple articles.

The first two relationships are one-to-many relationships. The tag relationship is many-to-many. In a relational database, a many-to-many relationship is usually stored through a join table rather than directly between two tables. This table will contain ArticleId and TagId as a composite primary key.

Entity versus ViewModel

Entity classes represent persistent records in the database. A ViewModel is designed for the requirements of a particular screen. For example, an article creation page may use a SelectedTagIds collection for tag selection. That property does not need to exist in the Article table.

Keeping this distinction is important. Using entity classes directly as form models can create problems with authorization, mass assignment, and client-submitted values as the application grows.

Creating the entity classes

Create a Data/Entities folder in the project. First, define the category, author, and tag classes:

namespace Cms.Web.Data.Entities;

public class Category
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public required string Slug { get; set; }
    public ICollection<Article> Articles { get; set; } = new List<Article>();
}

public class Author
{
    public int Id { get; set; }
    public required string DisplayName { get; set; }
    public required string Email { get; set; }
    public ICollection<Article> Articles { get; set; } = new List<Article>();
}

public class Tag
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public required string Slug { get; set; }
    public ICollection<ArticleTag> ArticleTags { get; set; } = new List<ArticleTag>();
}

By convention, the Id properties are recognized as primary keys. The collections named Articles and ArticleTags are navigation properties. They provide the object-oriented view of the relationships.

Initializing collections with empty lists reduces the need for null checks when a new entity is created. The C# required keyword tells the compiler that these properties must be assigned during object construction. We will also use the Fluent API to enforce required database columns.

Article and the join entity

namespace Cms.Web.Data.Entities;

public class Article
{
    public int Id { get; set; }
    public required string Title { get; set; }
    public required string Slug { get; set; }
    public required string Summary { get; set; }
    public required string Content { get; set; }
    public bool IsPublished { get; set; }
    public DateTime? PublishedAtUtc { get; set; }
    public DateTime CreatedAtUtc { get; set; }

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

    public int AuthorId { get; set; }
    public Author Author { get; set; } = null!;

    public ICollection<ArticleTag> ArticleTags { get; set; } = new List<ArticleTag>();
}

public class ArticleTag
{
    public int ArticleId { get; set; }
    public Article Article { get; set; } = null!;

    public int TagId { get; set; }
    public Tag Tag { get; set; } = null!;
}

CategoryId and AuthorId are foreign key properties. Because they are non-nullable, every article must have a category and an author. The null! operator tells the compiler that EF Core will populate the relationship; it does not allow null values to be stored in the database.

Creating the DbContext

Now create the context that includes the entity types in the EF Core model. This example assumes that the SQL Server provider packages are already installed.

using Cms.Web.Data.Entities;
using Microsoft.EntityFrameworkCore;

namespace Cms.Web.Data;

public class CmsDbContext(DbContextOptions<CmsDbContext> options)
    : DbContext(options)
{
    public DbSet<Article> Articles => Set<Article>();
    public DbSet<Category> Categories => Set<Category>();
    public DbSet<Author> Authors => Set<Author>();
    public DbSet<Tag> Tags => Set<Tag>();
    public DbSet<ArticleTag> ArticleTags => Set<ArticleTag>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.ApplyConfigurationsFromAssembly(
            typeof(CmsDbContext).Assembly);
    }
}

The DbSet properties make the entity types explicit in the context and provide a convenient way to write queries. Entity types can also be discovered through navigation properties or Fluent API configuration, but explicit sets make the model easier to understand.

Configuring relationships with the Fluent API

Instead of placing every rule in one large OnModelCreating method, we will create a separate configuration class for each entity. This keeps the model readable as the application grows.

Article configuration

using Cms.Web.Data.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Cms.Web.Data.Configurations;

public class ArticleConfiguration : IEntityTypeConfiguration<Article>
{
    public void Configure(EntityTypeBuilder<Article> builder)
    {
        builder.ToTable("Articles");
        builder.HasKey(article => article.Id);

        builder.Property(article => article.Title)
            .HasMaxLength(200)
            .IsRequired();

        builder.Property(article => article.Slug)
            .HasMaxLength(200)
            .IsRequired();

        builder.HasIndex(article => article.Slug)
            .IsUnique();

        builder.Property(article => article.Summary)
            .HasMaxLength(500)
            .IsRequired();

        builder.Property(article => article.Content)
            .IsRequired();

        builder.HasOne(article => article.Category)
            .WithMany(category => category.Articles)
            .HasForeignKey(article => article.CategoryId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasOne(article => article.Author)
            .WithMany(author => author.Articles)
            .HasForeignKey(article => article.AuthorId)
            .OnDelete(DeleteBehavior.Restrict);
    }
}

Making Slug unique prevents two articles from generating the same URL segment. Using Restrict for category and author relationships is also important. Automatically deleting all related articles when a category or author is deleted is usually unsafe for a CMS. If removal is required, move or archive the related articles first.

Category, Author, and Tag configurations

public class CategoryConfiguration : IEntityTypeConfiguration<Category>
{
    public void Configure(EntityTypeBuilder<Category> builder)
    {
        builder.ToTable("Categories");
        builder.HasKey(category => category.Id);
        builder.Property(category => category.Name)
            .HasMaxLength(100)
            .IsRequired();
        builder.Property(category => category.Slug)
            .HasMaxLength(120)
            .IsRequired();
        builder.HasIndex(category => category.Slug).IsUnique();
    }
}

public class AuthorConfiguration : IEntityTypeConfiguration<Author>
{
    public void Configure(EntityTypeBuilder<Author> builder)
    {
        builder.ToTable("Authors");
        builder.HasKey(author => author.Id);
        builder.Property(author => author.DisplayName)
            .HasMaxLength(120)
            .IsRequired();
        builder.Property(author => author.Email)
            .HasMaxLength(320)
            .IsRequired();
        builder.HasIndex(author => author.Email).IsUnique();
    }
}

public class TagConfiguration : IEntityTypeConfiguration<Tag>
{
    public void Configure(EntityTypeBuilder<Tag> builder)
    {
        builder.ToTable("Tags");
        builder.HasKey(tag => tag.Id);
        builder.Property(tag => tag.Name)
            .HasMaxLength(60)
            .IsRequired();
        builder.Property(tag => tag.Slug)
            .HasMaxLength(80)
            .IsRequired();
        builder.HasIndex(tag => tag.Slug).IsUnique();
    }
}

Configuring the many-to-many relationship

public class ArticleTagConfiguration : IEntityTypeConfiguration<ArticleTag>
{
    public void Configure(EntityTypeBuilder<ArticleTag> builder)
    {
        builder.ToTable("ArticleTags");
        builder.HasKey(articleTag => new
        {
            articleTag.ArticleId,
            articleTag.TagId
        });

        builder.HasOne(articleTag => articleTag.Article)
            .WithMany(article => article.ArticleTags)
            .HasForeignKey(articleTag => articleTag.ArticleId)
            .OnDelete(DeleteBehavior.Cascade);

        builder.HasOne(articleTag => articleTag.Tag)
            .WithMany(tag => tag.ArticleTags)
            .HasForeignKey(articleTag => articleTag.TagId)
            .OnDelete(DeleteBehavior.Cascade);
    }
}

The composite key prevents the same article-tag pair from being inserted more than once. When an article is deleted, removing its join rows is safe. However, deleting a tag or an article must not delete unrelated articles. Therefore, cascade behavior is limited to the join table connections.

Registering the context

Register the context in Program.cs using dependency injection:

using Cms.Web.Data;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

builder.Services.AddDbContext<CmsDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("CmsDatabase")));

var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

Keep the connection string in appsettings.json instead of embedding it directly in code:

{
  "ConnectionStrings": {
    "CmsDatabase": "Server=(localdb)\\MSSQLLocalDB;Database=CmsDb;Trusted_Connection=True;TrustServerCertificate=True"
  }
}

In real environments, do not commit passwords or sensitive connection strings to source control. Use environment variables, user secrets, or a secure secret store.

Common mistakes

  • Mixing entities and ViewModels: Using a database entity directly as a form model can allow clients to change fields they should not control.
  • Omitting foreign keys: Relationships may sometimes work through conventions, but explicit foreign key properties make querying, validation, and debugging clearer.
  • Not making slugs unique: Duplicate slugs can produce conflicting URLs.
  • Using Cascade everywhere: Deleting a category could unexpectedly delete all of its articles.
  • Leaving collections null: Uninitialized navigation collections increase the risk of null reference errors.
  • Relying only on HTML rules: Client-side validation improves the user experience; server-side rules and database constraints protect the data.

Short practice exercise

Complete the following exercise:

  1. Add MetaTitle and MetaDescription properties to Article.
  2. Configure maximum lengths of 60 and 160 characters.
  3. Allow an article to have no tags, but keep category and author relationships required.
  4. Write a query that loads the category and author with each article:
var articles = await dbContext.Articles
    .Include(article => article.Category)
    .Include(article => article.Author)
    .AsNoTracking()
    .ToListAsync();

Include adds related data to the query graph. AsNoTracking can reduce change-tracking overhead for read-only lists.

Conclusion

In this lesson, we created the core data model for our CMS. We modeled category and author relationships as one-to-many relationships, and represented the article-tag relationship as a many-to-many relationship through a join entity with a composite key. We also used the Fluent API to define column lengths, unique indexes, foreign keys, and delete behaviors.

In the next stage, we can create a migration for this model and generate the SQL Server database. The central idea of this lesson is to design database entities as representations of real business rules and relationships, not merely as unrelated classes.

Sources