.NET - Build a Blog System with ASP.NET Core and EF Core

Build a Blog System with ASP.NET Core and EF Core

Build a Blog System with ASP.NET Core and EF Core

Introduction

In this complete guide, we will build a fully functional Blog System using ASP.NET Core and Entity Framework Core (EF Core). This tutorial is aimed at developers who want to learn practical implementation of CRUD operations, authentication, and basic content management using modern .NET technologies.

What You Will Learn

  • Setting up an ASP.NET Core Web Application
  • Creating Models for Blog Posts, Categories, and Users
  • Setting up Entity Framework Core with Code-First Migrations
  • Implementing CRUD for blog posts
  • Adding authentication and authorization
  • Using Razor Pages or MVC to manage UI
  • Deploying the application

Prerequisites

  • .NET 7.0 or later
  • Visual Studio 2022+ or Visual Studio Code
  • SQL Server LocalDB or SQLite
  • Basic knowledge of C# and HTML

Step 1: Create the ASP.NET Core Project

Open Visual Studio and create a new ASP.NET Core Web Application. Choose either Web Application (Model-View-Controller) or Razor Pages as the project template. In this guide, we’ll use Razor Pages for simplicity.

dotnet new webapp -n BlogSystem

Install Required NuGet Packages

dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore

Step 2: Set Up the Data Models

Post.cs

public class Post
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public DateTime CreatedAt { get; set; } = DateTime.UtcNow;

    public int CategoryId { get; set; }
    public Category Category { get; set; }

    public string UserId { get; set; }
    public ApplicationUser User { get; set; }
}

Category.cs

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection Posts { get; set; }
}

ApplicationUser.cs

public class ApplicationUser : IdentityUser
{
    public ICollection Posts { get; set; }
}

Step 3: Configure the DbContext

BlogDbContext.cs

public class BlogDbContext : IdentityDbContext<ApplicationUser>
{
    public BlogDbContext(DbContextOptions<BlogDbContext> options) : base(options) { }

    public DbSet<Post> Posts { get; set; }
    public DbSet<Category> Categories { get; set; }
}

Step 4: Configure Services in Startup

Program.cs

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

builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
    .AddEntityFrameworkStores<BlogDbContext>();

builder.Services.AddRazorPages();

appsettings.json

"ConnectionStrings": {
  "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=BlogSystemDb;Trusted_Connection=True;"
}

Step 5: Run EF Core Migrations

dotnet ef migrations add InitialCreate
dotnet ef database update

Step 6: Create Razor Pages

Pages/Posts/Index.cshtml.cs

public class IndexModel : PageModel
{
    private readonly BlogDbContext _context;

    public IndexModel(BlogDbContext context)
    {
        _context = context;
    }

    public IList<Post> Posts { get; set; }

    public async Task OnGetAsync()
    {
        Posts = await _context.Posts.Include(p => p.Category).ToListAsync();
    }
}

Pages/Posts/Index.cshtml

@page
@model IndexModel

<h2>Blog Posts</h2>
<table>
@foreach (var post in Model.Posts)
{
    <tr>
        <td>@post.Title</td>
        <td>@post.Category.Name</td>
        <td>@post.CreatedAt.ToShortDateString()</td>
    </tr>
}
</table>

Step 7: Implement CRUD Operations

Repeat similar steps to create Razor Pages for:

  • Create.cshtml / Create.cshtml.cs
  • Edit.cshtml / Edit.cshtml.cs
  • Delete.cshtml / Delete.cshtml.cs
  • Details.cshtml / Details.cshtml.cs

Step 8: Add Authentication and Authorization

Protect Routes

[Authorize]
public class CreateModel : PageModel
{
    //...
}

Add Login and Register Pages

If using Individual User Accounts template, these are scaffolded by default. Ensure app.UseAuthentication() and app.UseAuthorization() are in your middleware pipeline.

Step 9: Create Layout and Navigation

Update _Layout.cshtml to add navigation to blog posts and account actions:

<ul class="navbar-nav">
    <li class="nav-item"><a class="nav-link" asp-page="/Posts/Index">Posts</a></li>
    <li class="nav-item"><a class="nav-link" asp-page="/Categories/Index">Categories</a></li>
    @if (User.Identity.IsAuthenticated)
    {
        <li class="nav-item"><a class="nav-link" asp-page="/Account/Logout">Logout</a></li>
    }
    else
    {
        <li class="nav-item"><a class="nav-link" asp-page="/Account/Login">Login</a></li>
    }
</ul>

Step 10: Add Category Management

Create CRUD Razor Pages for Category model similar to Post model.

Step 11: Extend Functionality

  • Add post tags
  • Enable markdown editing
  • Allow image uploads using IFormFile
  • Enable comments and likes
  • Add a search bar using LINQ

Step 12: Deploy the Blog System

Publish to Azure or IIS

dotnet publish -c Release -o ./publish

Host the application using Azure App Service, IIS, or any hosting that supports ASP.NET Core.

This tutorial gave you a complete walkthrough of how to build a scalable and secure Blog System using ASP.NET Core and Entity Framework Core. You now have the foundation to add advanced features like rich text editing, pagination, search, user roles, and SEO optimization.


Beginner 5 Hours
Build a Blog System with ASP.NET Core and EF Core

Build a Blog System with ASP.NET Core and EF Core

Introduction

In this complete guide, we will build a fully functional Blog System using ASP.NET Core and Entity Framework Core (EF Core). This tutorial is aimed at developers who want to learn practical implementation of CRUD operations, authentication, and basic content management using modern .NET technologies.

What You Will Learn

  • Setting up an ASP.NET Core Web Application
  • Creating Models for Blog Posts, Categories, and Users
  • Setting up Entity Framework Core with Code-First Migrations
  • Implementing CRUD for blog posts
  • Adding authentication and authorization
  • Using Razor Pages or MVC to manage UI
  • Deploying the application

Prerequisites

  • .NET 7.0 or later
  • Visual Studio 2022+ or Visual Studio Code
  • SQL Server LocalDB or SQLite
  • Basic knowledge of C# and HTML

Step 1: Create the ASP.NET Core Project

Open Visual Studio and create a new ASP.NET Core Web Application. Choose either Web Application (Model-View-Controller) or Razor Pages as the project template. In this guide, we’ll use Razor Pages for simplicity.

dotnet new webapp -n BlogSystem

Install Required NuGet Packages

dotnet add package Microsoft.EntityFrameworkCore dotnet add package Microsoft.EntityFrameworkCore.SqlServer dotnet add package Microsoft.EntityFrameworkCore.Tools dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore

Step 2: Set Up the Data Models

Post.cs

public class Post { public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } public DateTime CreatedAt { get; set; } = DateTime.UtcNow; public int CategoryId { get; set; } public Category Category { get; set; } public string UserId { get; set; } public ApplicationUser User { get; set; } }

Category.cs

public class Category { public int Id { get; set; } public string Name { get; set; } public ICollection Posts { get; set; } }

ApplicationUser.cs

public class ApplicationUser : IdentityUser { public ICollection Posts { get; set; } }

Step 3: Configure the DbContext

BlogDbContext.cs

public class BlogDbContext : IdentityDbContext<ApplicationUser> { public BlogDbContext(DbContextOptions<BlogDbContext> options) : base(options) { } public DbSet<Post> Posts { get; set; } public DbSet<Category> Categories { get; set; } }

Step 4: Configure Services in Startup

Program.cs

builder.Services.AddDbContext<BlogDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false) .AddEntityFrameworkStores<BlogDbContext>(); builder.Services.AddRazorPages();

appsettings.json

"ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=BlogSystemDb;Trusted_Connection=True;" }

Step 5: Run EF Core Migrations

dotnet ef migrations add InitialCreate dotnet ef database update

Step 6: Create Razor Pages

Pages/Posts/Index.cshtml.cs

public class IndexModel : PageModel { private readonly BlogDbContext _context; public IndexModel(BlogDbContext context) { _context = context; } public IList<Post> Posts { get; set; } public async Task OnGetAsync() { Posts = await _context.Posts.Include(p => p.Category).ToListAsync(); } }

Pages/Posts/Index.cshtml

@page @model IndexModel <h2>Blog Posts</h2> <table> @foreach (var post in Model.Posts) { <tr> <td>@post.Title</td> <td>@post.Category.Name</td> <td>@post.CreatedAt.ToShortDateString()</td> </tr> } </table>

Step 7: Implement CRUD Operations

Repeat similar steps to create Razor Pages for:

  • Create.cshtml / Create.cshtml.cs
  • Edit.cshtml / Edit.cshtml.cs
  • Delete.cshtml / Delete.cshtml.cs
  • Details.cshtml / Details.cshtml.cs

Step 8: Add Authentication and Authorization

Protect Routes

[Authorize] public class CreateModel : PageModel { //... }

Add Login and Register Pages

If using Individual User Accounts template, these are scaffolded by default. Ensure

app.UseAuthentication() and
app.UseAuthorization() are in your middleware pipeline.

Step 9: Create Layout and Navigation

Update _Layout.cshtml to add navigation to blog posts and account actions:

<ul class="navbar-nav"> <li class="nav-item"><a class="nav-link" asp-page="/Posts/Index">Posts</a></li> <li class="nav-item"><a class="nav-link" asp-page="/Categories/Index">Categories</a></li> @if (User.Identity.IsAuthenticated) { <li class="nav-item"><a class="nav-link" asp-page="/Account/Logout">Logout</a></li> } else { <li class="nav-item"><a class="nav-link" asp-page="/Account/Login">Login</a></li> } </ul>

Step 10: Add Category Management

Create CRUD Razor Pages for Category model similar to Post model.

Step 11: Extend Functionality

  • Add post tags
  • Enable markdown editing
  • Allow image uploads using IFormFile
  • Enable comments and likes
  • Add a search bar using LINQ

Step 12: Deploy the Blog System

Publish to Azure or IIS

dotnet publish -c Release -o ./publish

Host the application using Azure App Service, IIS, or any hosting that supports ASP.NET Core.

This tutorial gave you a complete walkthrough of how to build a scalable and secure Blog System using ASP.NET Core and Entity Framework Core. You now have the foundation to add advanced features like rich text editing, pagination, search, user roles, and SEO optimization.


Related Tutorials

Frequently Asked Questions for General

line

Copyrights © 2024 letsupdateskills All rights reserved