Introduction
In the previous lesson, we prepared the SQL Server connection, learned how to use DbContext, and managed migrations. We can now perform real operations on the content and category records stored in the database. In this lesson, we will implement CRUD, which stands for Create, Read, Update, and Delete, with ASP.NET Core MVC and Entity Framework Core.
CRUD is not just a matter of adding a few buttons and action methods. User input must be received and validated safely, content must be associated with the correct category, only permitted fields should be changed during editing, and deletion should be performed through a POST request. EF Core also already provides much of the behavior associated with repositories and units of work, so automatically adding repository classes to every project is not always the right choice.
1. Planning the CRUD flow
Our basic content-management flow will be:
- Listing: Retrieve content records and display them with their category information.
- Creation: Receive the title, summary, body, and category from the user.
- Editing: Read the existing record first, then update only permitted fields.
- Deletion: Display a confirmation page with GET and delete the record with POST.
This lesson uses the names ContentItem, Category, and ApplicationDbContext. If your project uses different names, map the examples to your own classes.
Example entity structure
public class ContentItem
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Slug { get; set; } = string.Empty;
public string Summary { get; set; } = string.Empty;
public string Body { get; set; } = string.Empty;
public int CategoryId { get; set; }
public Category Category { get; set; } = null!;
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public ICollection<ContentItem> ContentItems { get; set; } = new List<ContentItem>();
}If your entity classes contain validation attributes, MVC automatically builds ModelState after model binding. Every POST action should check ModelState.IsValid before sending data to the database.
2. Reading and listing records
The listing page usually starts with a GET action. Because this query is for reading, using AsNoTracking is appropriate; the user will not directly update the objects displayed on the list page. We use Include to load the related category so that its name can be displayed.
public class ContentsController : Controller
{
private readonly ApplicationDbContext _context;
public ContentsController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
var contents = await _context.ContentItems
.Include(c => c.Category)
.AsNoTracking()
.OrderByDescending(c => c.Id)
.ToListAsync();
return View(contents);
}
}The controller uses ApplicationDbContext directly. This is a readable starting point for small and medium-sized MVC applications. Because the query is visible, it is easy to understand exactly which data is being loaded.
3. Creating records safely
Instead of using the entity type directly as the POST parameter, let us use a ViewModel for the create screen. This means that we accept only the fields we explicitly want from the user. It reduces overposting risk: for example, a user cannot add an administrator-only property to the form and change a value that should not be editable.
public class ContentCreateViewModel
{
[Required, StringLength(150)]
public string Title { get; set; } = string.Empty;
[Required, StringLength(300)]
public string Summary { get; set; } = string.Empty;
[Required]
public string Body { get; set; } = string.Empty;
[Display(Name = "Category")]
[Range(1, int.MaxValue)]
public int CategoryId { get; set; }
}The GET action prepares the category list for the form. We can create a small helper method because the same list will also be needed when validation fails.
private async Task LoadCategoriesAsync(int? selectedCategoryId = null)
{
ViewBag.Categories = new SelectList(
await _context.Categories
.AsNoTracking()
.OrderBy(c => c.Name)
.ToListAsync(),
"Id",
"Name",
selectedCategoryId);
}
[HttpGet]
public async Task<IActionResult> Create()
{
await LoadCategoriesAsync();
return View(new ContentCreateViewModel());
}The POST action performs antiforgery validation, model validation, and a category existence check. In this lesson, we generate the slug simply from the title. In a real project, a separate slug service is preferable for handling non-ASCII characters, uniqueness, and collisions.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(ContentCreateViewModel model)
{
if (!ModelState.IsValid)
{
await LoadCategoriesAsync(model.CategoryId);
return View(model);
}
var categoryExists = await _context.Categories
.AnyAsync(c => c.Id == model.CategoryId);
if (!categoryExists)
{
ModelState.AddModelError(nameof(model.CategoryId), "The selected category was not found.");
await LoadCategoriesAsync(model.CategoryId);
return View(model);
}
var content = new ContentItem
{
Title = model.Title.Trim(),
Slug = SlugGenerator.Create(model.Title),
Summary = model.Summary.Trim(),
Body = model.Body,
CategoryId = model.CategoryId
};
_context.ContentItems.Add(content);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}SlugGenerator.Create represents a helper or service that exists, or that you will add later, in your project. If you do not have such a class yet, you can temporarily use the title, but you should eventually add a unique index and collision handling for slugs.
4. Editing existing records
A common and safe editing strategy is to reload the record from the database when the POST request arrives. We then change only the properties that the user is allowed to edit. Binding an entity from the form and marking it directly as Modified can update fields that the user did not intend to change.
[HttpGet]
public async Task<IActionResult> Edit(int? id)
{
if (id is null)
return NotFound();
var content = await _context.ContentItems
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == id.Value);
if (content is null)
return NotFound();
var model = new ContentCreateViewModel
{
Title = content.Title,
Summary = content.Summary,
Body = content.Body,
CategoryId = content.CategoryId
};
await LoadCategoriesAsync(model.CategoryId);
return View(model);
}The same ViewModel can be used for both create and edit screens. In a larger application, separate ContentCreateViewModel and ContentEditViewModel classes may make it easier to manage different fields and rules.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, ContentCreateViewModel model)
{
if (!ModelState.IsValid)
{
await LoadCategoriesAsync(model.CategoryId);
return View(model);
}
var content = await _context.ContentItems
.FirstOrDefaultAsync(c => c.Id == id);
if (content is null)
return NotFound();
var categoryExists = await _context.Categories
.AnyAsync(c => c.Id == model.CategoryId);
if (!categoryExists)
{
ModelState.AddModelError(nameof(model.CategoryId), "The selected category was not found.");
await LoadCategoriesAsync(model.CategoryId);
return View(model);
}
content.Title = model.Title.Trim();
content.Slug = SlugGenerator.Create(model.Title);
content.Summary = model.Summary.Trim();
content.Body = model.Body;
content.CategoryId = model.CategoryId;
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}The entity is tracked by the context in this request. When its properties change, EF Core recognizes the entity as Modified and generates an UPDATE command when SaveChangesAsync is called.
5. Deleting records
Performing deletion through a GET link is not safe. Search engines, preview tools, or an unintended request could visit a GET URL. Therefore, the GET action should display only a confirmation page, while the actual deletion should happen in a POST action protected by an antiforgery token.
[HttpGet]
public async Task<IActionResult> Delete(int? id)
{
if (id is null)
return NotFound();
var content = await _context.ContentItems
.Include(c => c.Category)
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == id.Value);
if (content is null)
return NotFound();
return View(content);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var content = await _context.ContentItems
.FirstOrDefaultAsync(c => c.Id == id);
if (content is null)
return RedirectToAction(nameof(Index));
_context.ContentItems.Remove(content);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}The Delete view should contain a regular MVC form and a submit button. The Razor form tag helper can generate an antiforgery token; nevertheless, explicitly applying ValidateAntiForgeryToken to the controller action makes the security requirement clear. If other tables reference the content row, a foreign-key constraint may cause a DbUpdateException. You can catch that exception and show a helpful message, or use a soft-delete field such as IsDeleted instead of physically removing the record.
6. Where should the repository approach be used?
A repository is an abstraction that separates database operations from the rest of the application. However, an EF Core DbSet behaves like a queryable collection, and DbContext already provides much of the repository and unit-of-work behavior required by many applications.
For that reason, automatically creating a generic class like this for every entity is often unnecessary:
public interface IRepository<T>
{
Task<T?> GetByIdAsync(int id);
Task<IReadOnlyList<T>> GetAllAsync();
Task AddAsync(T entity);
void Update(T entity);
void Delete(T entity);
}This type of layer can hide EF Core features such as Include, AsNoTracking, filtering, and projection. The controller may look more abstract, but query flexibility can decrease. In a small MVC application, direct DbContext usage may be clearer and require less code.
A repository can become useful when:
- You must strictly separate data access from the domain or application layer.
- The same data queries are repeated in many places.
- You combine multiple data sources behind one application interface.
- You specifically want controlled test doubles instead of using a real database in unit tests.
- You need cross-cutting behavior such as caching, logging, tenant filtering, or custom transaction handling.
For this course, we use DbContext directly at this stage. This does not reject the repository pattern; it means that we add an abstraction when a real need appears. If publishing workflows, slug uniqueness, searching, and authorization become more complex, we can introduce an IContentRepository or a domain-focused application service.
7. Common mistakes
- Deleting in a GET action: Use GET only for the confirmation screen.
- Forgetting antiforgery validation: Use
ValidateAntiForgeryTokenon MVC actions that modify data. - Binding the entity directly from the form: Use a ViewModel to reduce overposting risk.
- Trusting an arbitrary category ID: Verify that the category exists in the POST action.
- Tracking every list query: Prefer
AsNoTrackingfor read-only queries. - Adding repositories only because they are fashionable: An abstraction should solve a real maintenance, testing, or architectural problem.
- Not rebuilding the category list after a validation error: Recreate the ViewBag or ViewModel selection data before returning the view.
8. Short practice exercise
Finish an incomplete CRUD flow for ContentsController in your application. Add the Index, Create, Edit, and Delete actions, then perform these checks:
- Verify that a record cannot be created with an empty title.
- Submit an invalid category ID and confirm that server-side validation catches it.
- Change the ID in the edit URL and observe that a missing record returns
NotFound. - Remove the antiforgery field from the delete confirmation form and verify that the request is rejected.
- Confirm that the listing query includes both
AsNoTrackingand the categoryInclude.
Conclusion
In this lesson, we built a complete CRUD flow for content and category management with EF Core. We loaded related data while listing records, used ViewModels for safer model binding during creation and editing, and implemented deletion as a POST operation protected by antiforgery validation.
We also saw that the repository approach is not a pattern that must be added automatically to every project. EF Core's DbContext is sufficient as a repository and unit of work for many applications. When the application grows, adding a focused, meaningful, and testable abstraction is usually healthier than wrapping every EF Core method in a generic repository. In upcoming lessons, we will improve these CRUD screens with better user experience, searching, pagination, and authorization.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/crud?view=aspnetcore-8.0
- https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-6.0
- https://learn.microsoft.com/en-us/aspnet/core/security/anti-request-forgery
- https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/advanced
- https://learn.microsoft.com/en-us/ef/core/api/microsoft.entityframeworkcore.dbcontext