Entity Framework Core Basics
This tutorial guides you through the fundamental concepts of using Entity Framework Core (EF Core) to interact with your database in .NET applications. EF Core is a modern object-relational mapper (ORM) for .NET that enables developers to work with a database using .NET objects, eliminating the need for most of the data-access code they typically need to write.
What is Entity Framework Core?
EF Core is an open-source, cross-platform, extensible data access technology for .NET. It allows you to query and save data to relational databases.
- Object-Relational Mapping (ORM): Maps your .NET classes to database tables.
- Database Agnostic: Supports various database providers (SQL Server, PostgreSQL, MySQL, SQLite, etc.).
- LINQ Integration: Enables querying your database using Language Integrated Query (LINQ).
- Migrations: Manages database schema changes over time.
Setting Up Your Project
Before we start, ensure you have the necessary .NET SDK installed. We'll use a simple Console Application for this tutorial.
1. Create a New Project
Open your terminal or command prompt and run the following command:
dotnet new console -o EFCoreTutorial
Navigate into the project directory:
cd EFCoreTutorial
2. Install EF Core Packages
You'll need to install the EF Core NuGet packages. For this tutorial, we'll use the SQL Server provider. If you prefer a different database, replace the provider package accordingly.
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
The Microsoft.EntityFrameworkCore.Tools package is needed for migrations.
Defining Your Model
Define the C# classes that represent the entities you want to store in your database. These classes will be mapped to database tables.
1. Create an Entity Class
Create a new file named Models/Blog.cs and add the following code:
namespace EFCoreTutorial.Models
{
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List Posts { get; set; }
}
}
Now, create a Post class in the same directory:
namespace EFCoreTutorial.Models
{
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; }
}
}
EF Core uses conventions to infer the database schema. By default, it recognizes properties named Id or ClassNameId as primary keys.
Creating Your DbContext
The DbContext is the main class that represents a session with the database and allows you to query and save data. It's a bridge between your object-oriented code and the relational database.
1. Create the DbContext Class
Create a new file named BloggingContext.cs in the root of your project:
using Microsoft.EntityFrameworkCore;
using EFCoreTutorial.Models;
namespace EFCoreTutorial
{
public class BloggingContext : DbContext
{
public DbSet Blogs { get; set; }
public DbSet Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Replace with your actual connection string
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=EFCoreTutorialDb;Trusted_Connection=True;");
}
}
}
appsettings.json) rather than hardcoding them.
Database Migrations
Migrations are used to incrementally update your database schema to match your entity model. EF Core Migrations is a feature that enables you to evolve your database schema over time as your application's data model changes.
1. Enable Migrations
In the terminal, run the following command:
dotnet ef migrations add InitialCreate
This command generates a migration file that contains instructions to create the database tables based on your DbContext and entity models.
2. Apply Migrations
To create the database and tables on your SQL Server instance, run:
dotnet ef database update
This will create a database named EFCoreTutorialDb (or whatever you specified in your connection string) and create the Blogs and Posts tables.
Interacting with the Database
Now, let's use our DbContext to perform CRUD (Create, Read, Update, Delete) operations.
1. Creating Data
Modify your Program.cs file:
using EFCoreTutorial;
using EFCoreTutorial.Models;
using (var context = new BloggingContext())
{
Console.WriteLine("Adding a new blog...");
var newBlog = new Blog { Url = "https://example.com/blog" };
context.Blogs.Add(newBlog);
context.SaveChanges();
Console.WriteLine($"Blog added with ID: {newBlog.BlogId}");
Console.WriteLine("Adding a new post...");
var newPost = new Post { Title = "Introduction to EF Core", Content = "This is the first post.", BlogId = newBlog.BlogId };
context.Posts.Add(newPost);
context.SaveChanges();
Console.WriteLine($"Post added with ID: {newPost.PostId}");
}
2. Reading Data
Add the following code to your Program.cs to read data:
using (var context = new BloggingContext())
{
Console.WriteLine("\nReading blogs:");
var blogs = context.Blogs.ToList(); // Use ToList() to execute the query
foreach (var blog in blogs)
{
Console.WriteLine($"- {blog.Url} (ID: {blog.BlogId})");
}
Console.WriteLine("\nReading posts for a specific blog:");
var blogWithPosts = context.Blogs.Where(b => b.BlogId == 1).FirstOrDefault(); // Example: retrieve blog with ID 1
if (blogWithPosts != null)
{
Console.WriteLine($"Posts for blog at {blogWithPosts.Url}:");
foreach (var post in blogWithPosts.Posts) // Lazy loading if configured, or eager loading if specified
{
Console.WriteLine($"- {post.Title}");
}
}
}
.Include()) or explicit loading to control when related data is fetched.
3. Updating Data
Add the following code to update data:
using (var context = new BloggingContext())
{
Console.WriteLine("\nUpdating a blog...");
var blogToUpdate = context.Blogs.Find(1); // Find by primary key
if (blogToUpdate != null)
{
blogToUpdate.Url = "https://updated-example.com/blog";
context.SaveChanges();
Console.WriteLine($"Blog with ID {blogToUpdate.BlogId} updated.");
}
}
4. Deleting Data
Add the following code to delete data:
using (var context = new BloggingContext())
{
Console.WriteLine("\nDeleting a post...");
var postToDelete = context.Posts.Find(1); // Assuming a post with ID 1 exists
if (postToDelete != null)
{
context.Posts.Remove(postToDelete);
context.SaveChanges();
Console.WriteLine($"Post with ID {postToDelete.PostId} deleted.");
}
Console.WriteLine("\nDeleting a blog and its posts (cascading delete)...");
// If cascade delete is configured on the relationship, deleting the blog will delete its posts.
var blogToDelete = context.Blogs.Find(1); // Assuming blog with ID 1 exists
if (blogToDelete != null)
{
context.Blogs.Remove(blogToDelete);
context.SaveChanges();
Console.WriteLine($"Blog with ID {blogToDelete.BlogId} and its related posts deleted.");
}
}
Conclusion
You have now learned the basics of using Entity Framework Core: defining models, creating a DbContext, performing database migrations, and executing CRUD operations. EF Core offers a powerful and flexible way to manage data in your .NET applications.
Explore further to learn about advanced topics such as: