Data Access with Entity Framework Core
From the Asp. Net, mvc, c# basic 00 to advance curriculum
TL;DR
Entity Framework Core (EF Core) is an Object-Relational Mapper (ORM) that lets you interact with databases using C# objects. It translates your C# code into database queries, simplifying data access in ASP.NET MVC applications. You'll define your database schema using C# classes and EF Core will handle the heavy lifting of creating and managing the database.
1. The Mental Model
Think of EF Core as a translator between your C# application and your database. Instead of writing SQL queries directly, you'll work with C# objects, and EF Core will figure out the right SQL to send to the database, bringing the data back as C# objects.
2. The Core Material
EF Core provides a way to map your C# classes (your "models") to database tables. This mapping allows you to query, insert, update, and delete data using familiar C# syntax.
Defining Your Data Model

Photo by RDNE Stock project on Pexels
First, you define C# classes that represent your database tables. These are often called entity classes.
// Models/Product.cs
public class Product
{
public int ProductId { get; set; } // Primary Key (EF Core convention)
public string Name { get; set; }
public decimal Price { get; set; }
}
The DbContext

Photo by Nicolas Foster on Pexels
The DbContext is the main class in EF Core that manages your database interactions. It represents a session with the database and contains DbSet properties for each of your entity classes.
// Data/ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Product> Products { get; set; } // Represents the Products table
}
Configuring EF Core

Photo by panumas nikhomkhai on Pexels
You configure EF Core in your ASP.NET Core application's Program.cs file (or Startup.cs in older versions). This is where you tell EF Core which database provider to use (e.g., SQL Server, SQLite) and provide the connection string.
// Program.cs
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
The DefaultConnection string would be in your appsettings.json.
Migrations
Migrations are how EF Core manages changes to your database schema as your models evolve. When you make changes to your entity classes (e.g., add a new property), you create a migration to update the database schema.
# In Package Manager Console (Visual Studio) or terminal
dotnet ef migrations add InitialCreate
dotnet ef database update
Performing CRUD Operations

Photo by SHOX ART on Pexels
Once set up, you can perform Create, Read, Update, and Delete (CRUD) operations easily.
Reading Data
// Get all products
var allProducts = _context.Products.ToList();
// Get a product by ID
var product = _context.Products.Find(1); // Finds by primary key
// Get products with specific criteria
var expensiveProducts = _context.Products
.Where(p => p.Price > 100)
.OrderBy(p => p.Name)
.ToList();
Creating Data
var newProduct = new Product { Name = "Laptop", Price = 1200.00m };
_context.Products.Add(newProduct);
_context.SaveChanges(); // Persists changes to the database
Updating Data
var productToUpdate = _context.Products.Find(1);
if (productToUpdate != null)
{
productToUpdate.Price = 1250.00m;
_context.SaveChanges();
}
Deleting Data
var productToDelete = _context.Products.Find(2);
if (productToDelete != null)
{
_context.Products.Remove(productToDelete);
_context.SaveChanges();
}
Here's how the EF Core data flow generally works:
graph TD
A["ASP.NET MVC Controller Action"] --> B["Inject DbContext"];
B --> C["Call DbSet methods (e.g., .Add(), .Where(), .Find())"];
C --> D["EF Core translates C# to SQL"];
D --> E["Database executes SQL"];
E --> F["Database returns results"];
F --> G["EF Core materializes results into C# objects"];
G --> H["C# objects returned to Controller"];
H --> I["View renders data"];
3. Worked Example
Let's say you want to display a list of products in an ASP.NET MVC view.
- Define your
Productmodel (as above). - Define your
ApplicationDbContext(as above). - Configure
DbContextinProgram.cs(as above). - Create initial migration and update database:
dotnet ef migrations add InitialCreate
dotnet ef database update -
Create a Controller:
```csharp
// Controllers/ProductsController.cs
using Microsoft.AspNetCore.Mvc;
using YourAppNamespace.Data; // Adjust namespace
using YourAppNamespace.Models; // Adjust namespace
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;public class ProductsController : Controller
{
private readonly ApplicationDbContext _context;public ProductsController(ApplicationDbContext context) { _context = context; } // GET: /Products public async Task<IActionResult> Index() { var products = await _context.Products.ToListAsync(); return View(products); } // GET: /Products/Create public IActionResult Create() { return View(); } // POST: /Products/Create [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Name,Price")] Product product) { if (ModelState.IsValid) { _context.Add(product); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(product); }}
6. **Create a View to display products**:html
@model IEnumerable@{
ViewData["Title"] = "Products";
}Products
@Html.DisplayNameFor(model => model.Name)
@Html.DisplayNameFor(model => model.Price)
@foreach (var item in Model) {
@Html.DisplayFor(modelItem => item.Name)
@Html.DisplayFor(modelItem => item.Price)
}
`` When you navigate to/Products, theIndex` action will fetch all products from the database using EF Core and pass them to the view, which then displays them.
4. Key Takeaways
- EF Core is an ORM that simplifies database interactions by mapping C# objects to database tables.
- You define entity classes (plain C# objects) to represent your data schema.
- The
DbContextclass is your primary interface for querying and saving data. DbSet<T>properties on yourDbContextrepresent collections of entities in your database.- Migrations are crucial for evolving your database schema alongside your application's models.
- Call
_context.SaveChanges()to persist any changes (adds, updates, deletes) to the database. - EF Core integrates seamlessly with ASP.NET Core's dependency injection for
DbContextinstances.
Common Mistakes to Avoid
- Forgetting
_context.SaveChanges(): Changes made toDbSetare not persisted untilSaveChanges()is called. - Not running migrations: If your database schema doesn't match your models, you'll get errors. Always run
dotnet ef database updateafterdotnet ef migrations add. - N+1 problem with lazy loading: Repeatedly fetching related data in a loop can lead to many small, inefficient queries. Use
Include()for eager loading to fetch related data efficiently. - Not disposing
DbContextproperly: In web applications,DbContextis typically managed by the dependency injection container, which handles its lifetime. Avoid manually creatingDbContextinstances outside of specific scenarios.
5. Now Try It
Create a new ASP.NET Core MVC project. Define a simple Category model with CategoryId and Name properties. Add a DbSet<Category> to your ApplicationDbContext. Configure EF Core to use an in-memory database for simplicity (replace UseSqlServer with UseInMemoryDatabase("MyCategoriesDb")). Create a CategoriesController with an Index action that retrieves all categories and a Create action to add new ones. Finally, build a corresponding Index.cshtml view to display your categories and a Create.cshtml view with a form to add new ones.
Success looks like: You can run your application, navigate to /Categories, see an empty list (initially), and then successfully add new categories via the "Create New" link, which then appear in your list.
Frequently asked about Data Access with Entity Framework Core
Study this next
Get the full Asp. Net, mvc, c# basic 00 to advance curriculum
Clone the complete plan to your dashboard for unlimited AI-generated notes, practice quizzes, and a personalised revision schedule.
Save this course free