ASP.NET Tutorial: CRUD Operations with EF Core

beginner
23 min

ASP.NET Tutorial: CRUD Operations with EF Core

Welcome to CodeYourCraft's comprehensive guide on CRUD (Create, Read, Update, Delete) Operations with Entity Framework Core (EF Core)! This tutorial is designed for beginners and intermediate learners, explaining concepts from the ground up. Let's dive into the world of ASP.NET and EF Core!

What is EF Core?

Entity Framework Core (EF Core) is a lightweight, modern, and open-source Object-Relational Mapping (ORM) framework that allows .NET developers to work with relational databases more efficiently.

šŸ’” Pro Tip: EF Core simplifies data access by abstracting the database operations, making it easier to work with databases and reducing the amount of boilerplate code.

Setting Up Your Project

First, let's create a new ASP.NET Core Web Application (API) project.

dotnet new webapi -n EFCoreCrud cd EFCoreCrud

šŸ“ Note: We're creating an API project because we'll be working with data services.

Installing EF Core and Other Dependencies

Next, we'll add the necessary packages to our project:

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

These packages include Entity Framework Core itself, the SQL Server provider for EF Core, and some design-time tools.

Creating Our Model

Now, let's create a simple model for a Book entity:

csharp
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace EFCoreCrud.Models { public class Book { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] [MaxLength(100)] public string Title { get; set; } [Required] [MaxLength(200)] public string Author { get; set; } [Required] [Range(1, int.MaxValue)] public int PageCount { get; set; } } }

šŸ’” Pro Tip: The [Key] attribute marks the primary key of the entity, while the [DatabaseGenerated] attribute specifies how the primary key should be generated.

Configuring DbContext

Next, let's create a DbContext class to manage our database context:

csharp
using Microsoft.EntityFrameworkCore; namespace EFCoreCrud { public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Book> Books { get; set; } } }

šŸ’” Pro Tip: DbSet is a property of the DbContext class that allows us to query and manipulate the corresponding entity.

Performing CRUD Operations

Now that we have our model and DbContext configured, let's see how to perform CRUD operations using EF Core.

Creating (C)

csharp
public IActionResult Create(Book book) { _context.Books.Add(book); _context.SaveChanges(); return Ok(book); }

šŸ“ Note: _context is an instance of ApplicationDbContext.

Reading (R)

csharp
public async Task<IActionResult> GetBookById(int id) { var book = await _context.Books.FindAsync(id); if (book == null) { return NotFound(); } return Ok(book); }

šŸ’” Pro Tip: The FindAsync method retrieves an entity by its primary key.

Updating (U)

csharp
public IActionResult Update(Book book) { var existingBook = _context.Books.Find(book.Id); if (existingBook == null) { return NotFound(); } _context.Entry(existingBook).CurrentValues.SetValues(book); _context.SaveChanges(); return Ok(book); }

šŸ’” Pro Tip: The Entry method allows us to manipulate an existing entity in the database context.

Deleting (D)

csharp
public IActionResult Delete(int id) { var book = _context.Books.Find(id); if (book == null) { return NotFound(); } _context.Books.Remove(book); _context.SaveChanges(); return Ok(book); }

šŸ’” Pro Tip: The Remove method removes an entity from the database context.

Quiz

Quick Quiz
Question 1 of 1

What does the `[Key]` attribute do in EF Core?

That's it for this tutorial! You now have a solid understanding of how to perform CRUD operations with EF Core in ASP.NET. Happy coding! šŸŽ‰

šŸ“ Note: In a real-world project, you'll want to handle errors more gracefully and create a repository pattern for better separation of concerns.

Stay tuned for more tutorials on CodeYourCraft! šŸš€


This tutorial is designed to be beginner-friendly while also providing enough depth for intermediate learners. It covers essential topics related to CRUD operations with EF Core and ASP.NET. We hope you found this tutorial helpful and informative! šŸŽ‰šŸŽÆ