Entity Framework Core CRUD Tutorial: Create, Read, Update, and Delete Data in ASP.NET Core
Entity Framework Core (EF Core) is Microsoft's modern Object-Relational Mapper (ORM) for .NET applications. It allows developers to work with databases using C# objects instead of writing large amounts of SQL code.
One of the most common tasks in application development is performing CRUD operations: Create, Read, Update, and Delete. In this tutorial, you'll learn how to implement CRUD functionality using Entity Framework Core in an ASP.NET Core application.
- What is Entity Framework Core?
- Installing EF Core
- Creating Models
- Creating DbContext
- Database Migrations
- Create Records
- Read Records
- Update Records
- Delete Records
- Best Practices
What Is Entity Framework Core?
Entity Framework Core is an open-source ORM that simplifies database development by mapping database tables to C# classes.
Instead of manually writing SQL queries for every operation, developers can use LINQ and C# code to interact with data.
EF Core supports:
- SQL Server
- MySQL
- PostgreSQL
- SQLite
- Oracle
- Azure SQL Database
Understanding CRUD Operations
| Operation | Description |
|---|---|
| Create | Add new records. |
| Read | Retrieve records. |
| Update | Modify existing records. |
| Delete | Remove records. |
Create a New ASP.NET Core Project
dotnet new mvc -n EfCoreCrudDemo
cd EfCoreCrudDemo
Install Entity Framework Core Packages
dotnet add package
Microsoft.EntityFrameworkCore
dotnet add package
Microsoft.EntityFrameworkCore.SqlServer
dotnet add package
Microsoft.EntityFrameworkCore.Tools
These packages provide EF Core functionality and SQL Server support.
Create the Product Model
Models represent data stored in the database.
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = "";
public decimal Price { get; set; }
public int Stock { get; set; }
}
Create the Database Context
DbContext acts as the bridge between your application and the database.
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext
: DbContext
{
public ApplicationDbContext(
DbContextOptions<ApplicationDbContext>
options)
: base(options)
{
}
public DbSet<Product> Products
{
get; set;
}
}
Configure the Database Connection
Add a connection string to appsettings.json.
{
"ConnectionStrings": {
"DefaultConnection":
"Server=(localdb)\\MSSQLLocalDB;
Database=EfCoreCrudDemo;
Trusted_Connection=True;"
}
}
Register DbContext
Register the database context inside Program.cs.
builder.Services.AddDbContext
<ApplicationDbContext>(options =>
{
options.UseSqlServer(
builder.Configuration
.GetConnectionString(
"DefaultConnection"));
});
Create the Initial Migration
Migrations create and update the database schema.
dotnet ef migrations add InitialCreate
dotnet ef database update
EF Core will generate the Products table automatically.
Create (Insert Data)
The Create operation adds new records to the database.
public async Task CreateProduct()
{
Product product = new Product
{
Name = "Laptop",
Price = 999.99M,
Stock = 10
};
_context.Products.Add(product);
await _context.SaveChangesAsync();
}
SaveChangesAsync commits the changes to the database.
Read (Retrieve Data)
The Read operation retrieves records.
var products =
await _context.Products
.ToListAsync();
Retrieve a single product:
var product =
await _context.Products
.FirstOrDefaultAsync(
p => p.Id == 1);
Display Data in a View
public async Task<IActionResult> Index()
{
var products =
await _context.Products
.ToListAsync();
return View(products);
}
@@model tIEnumerable<Product>
<table>
@@foreach(var product in Model)
{
<tr>
<td>@@product.Name</td>
<td>@@product.Price</td>
</tr>
}
</table>
Update Records
Updating modifies existing records.
var product =
await _context.Products
.FindAsync(1);
if(product != null)
{
product.Price = 1099.99M;
await _context.SaveChangesAsync();
}
EF Core automatically tracks changes to entities.
Delete Records
Delete removes data from the database.
var product =
await _context.Products
.FindAsync(1);
if(product != null)
{
_context.Products.Remove(product);
await _context.SaveChangesAsync();
}
Creating a CRUD Controller
Controllers are commonly used to manage CRUD functionality.
public class ProductsController
: Controller
{
private readonly
ApplicationDbContext _context;
public ProductsController(
ApplicationDbContext context)
{
_context = context;
}
}
Dependency Injection provides access to the database context.
Using LINQ with EF Core
LINQ makes querying data simple and readable.
var expensiveProducts =
await _context.Products
.Where(p => p.Price > 500)
.ToListAsync();
var orderedProducts =
await _context.Products
.OrderBy(p => p.Name)
.ToListAsync();
Async Database Operations
Use asynchronous methods whenever possible.
- ToListAsync()
- FirstOrDefaultAsync()
- FindAsync()
- SaveChangesAsync()
Async operations improve scalability and responsiveness.
Common Beginner Mistakes
- Forgetting SaveChangesAsync().
- Not creating migrations.
- Hard-coding connection strings.
- Ignoring async methods.
- Loading unnecessary data.
Best Practices
- Use Dependency Injection.
- Use async database operations.
- Keep DbContext short-lived.
- Validate user input.
- Use migrations for schema changes.
- Use LINQ effectively.
Frequently Asked Questions
Is Entity Framework Core free?
Yes. Entity Framework Core is open-source and free to use.
Do I need SQL knowledge?
Basic SQL knowledge is helpful, but EF Core allows you to perform most operations using C# and LINQ.
Should I use async methods?
Yes. Async methods improve application performance and scalability, especially in web applications.
Can EF Core work with ASP.NET Core MVC?
Absolutely. EF Core is commonly used with ASP.NET Core MVC and Web APIs.
Related Tutorials
- ASP.NET Core MVC Tutorial
- Entity Framework Core CRUD
- LINQ Cheat Sheet
- Repository Pattern in ASP.NET Core
- Entity Framework Core Migrations
- Build a REST API in ASP.NET Core
Conclusion
Entity Framework Core simplifies database development by allowing developers to work with C# objects instead of manually writing large amounts of SQL.
Understanding CRUD operations is a fundamental skill for building ASP.NET Core applications. Once you're comfortable creating, reading, updating, and deleting data, you'll be ready to explore advanced topics such as relationships, repositories, migrations, performance optimization, and database design.