Getting Started with Entity Framework Core
Entity Framework Core (EF Core) is a modern object-relational mapper (ORM) for .NET. It allows developers to work with databases using .NET objects and LINQ queries, abstracting away much of the underlying SQL complexity.
What is Entity Framework Core?
EF Core provides a set of APIs and tools that simplify data access in .NET applications. It supports various database providers, including SQL Server, SQLite, PostgreSQL, MySQL, and more. With EF Core, you can:
- Define your database schema using .NET classes (Code-First approach).
- Map existing database tables to .NET classes (Database-First approach).
- Perform CRUD (Create, Read, Update, Delete) operations seamlessly.
- Execute complex queries using Language Integrated Query (LINQ).
- Manage database migrations to evolve your schema over time.
Prerequisites
Before you begin, ensure you have the following installed:
- .NET SDK (version 6.0 or later recommended).
- A code editor like Visual Studio, VS Code, or JetBrains Rider.
- A database installed if you plan to work with an existing database (e.g., SQL Server Express, SQLite).
Installation
You can install EF Core using NuGet Package Manager or the .NET CLI. The core packages you'll typically need are:
Microsoft.EntityFrameworkCore
: The EF Core runtime.Microsoft.EntityFrameworkCore.Tools
: For design-time operations like migrations (install globally or per project).- A database provider package (e.g.,
Microsoft.EntityFrameworkCore.SqlServer
,Microsoft.EntityFrameworkCore.Sqlite
).
To install using the .NET CLI:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package Microsoft.EntityFrameworkCore.SqlServer # Or your chosen provider
Creating Your First EF Core Model
Let's define a simple model representing a blog and its posts:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
Creating Your DbContext
A DbContext
represents a session with the database and allows you to query and save data. It's also the entry point for EF Core configuration.
using Microsoft.EntityFrameworkCore;
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public BloggingContext(DbContextOptions<BloggingContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Optional: Configure relationships or constraints here
modelBuilder.Entity<Blog>()
.HasMany(b => b.Posts)
.WithOne(p => p.Blog);
}
}
Configuring Your DbContext
You need to tell your application how to connect to the database. This is typically done in your application's startup configuration (e.g., Program.cs
in .NET 6+).
// In Program.cs (for .NET 6+ Minimal APIs)
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
var connectionString = builder.Configuration.GetConnectionString("BloggingDatabase");
builder.Services.AddDbContext<BloggingContext>(options =>
options.UseSqlServer(connectionString)); // Or UseSqlite, UseNpgsql, etc.
var app = builder.Build();
// ... rest of your configuration ...
Ensure you have a connection string defined in your appsettings.json
:
{
"ConnectionStrings": {
"BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=Blogging;Trusted_Connection=True;"
}
}
Database Migrations
Migrations allow you to incrementally update your database schema as your model changes. This is crucial for evolving your application.
Add a Migration:
dotnet ef migrations add InitialCreate
Update the Database:
dotnet ef database update
Querying Data
Once your database is set up, you can query data using LINQ.
// Assuming you have injected BloggingContext into your service/page
public async Task<IActionResult> OnGet()
{
var blogs = await _context.Blogs
.OrderBy(b => b.Url)
.ToListAsync();
return Page(); // Or return the data
}
Saving Data
Adding, modifying, and deleting data is straightforward.
// Add a new blog
var newBlog = new Blog { Url = "http://example.com" };
_context.Blogs.Add(newBlog);
await _context.SaveChangesAsync();
// Update a blog
var existingBlog = await _context.Blogs.FindAsync(1);
if (existingBlog != null)
{
existingBlog.Url = "http://updated.com";
await _context.SaveChangesAsync();
}
// Delete a blog
var blogToDelete = await _context.Blogs.FindAsync(2);
if (blogToDelete != null)
{
_context.Blogs.Remove(blogToDelete);
await _context.SaveChangesAsync();
}
Next Steps
This guide provides a basic introduction. Explore the following resources for deeper dives: