Entity Framework Core: Getting Started
Welcome to the Entity Framework Core (EF Core) getting started guide. This tutorial will walk you through the fundamental steps of setting up and using EF Core in your .NET applications.
What is Entity Framework Core?
Entity Framework Core (EF Core) is a modern, cross-platform, open-source, and extensible version of the classic Entity Framework data access technology. It allows .NET developers to work with databases using .NET objects, abstracting away much of the complex SQL code.
Note: EF Core supports a variety of database providers, including SQL Server, SQLite, MySQL, PostgreSQL, and more.
Prerequisites
- .NET SDK (version 6.0 or later recommended)
- A code editor (Visual Studio, VS Code, etc.)
- Basic understanding of C# and object-oriented programming.
Step 1: Create a New Project
First, let's create a new .NET Console Application. Open your terminal or command prompt and run the following command:
dotnet new console -o EFCoreGettingStarted
cd EFCoreGettingStarted
Step 2: Install EF Core NuGet Packages
Next, you need to install the EF Core NuGet packages. For this example, we'll use the SQL Server provider. If you plan to use a different database, install the corresponding provider package.
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
The Microsoft.EntityFrameworkCore.Tools package is essential for database migrations.
Step 3: Define Your Model
Let's define a simple model representing a blog and its posts.
// Models/Blog.cs
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
// Models/Post.cs
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; }
}
Step 4: Create Your DbContext
The DbContext class is the main entry point for interacting with your database. It represents a session with the database and allows you to query and save data.
// Data/BloggingContext.cs
using Microsoft.EntityFrameworkCore;
using EFCoreGettingStarted.Models;
namespace EFCoreGettingStarted.Data
{
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 OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Uncomment and configure if not using dependency injection
// optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=BloggingEFCore;Trusted_Connection=True;");
}
}
}
Tip: For ASP.NET Core applications, you'll typically configure your DbContext using Dependency Injection in the Startup.cs or Program.cs file.
Step 5: Configure the Connection String
You need to tell EF Core how to connect to your database. For a console application, you can override OnConfiguring or configure it via dependency injection.
In this example, we'll show how to configure it within the Program.cs file for a console app using a simple in-memory provider for ease of demonstration, but you would use SQL Server or another provider for a real application.
// Program.cs (Simplified for demonstration)
using Microsoft.EntityFrameworkCore;
using EFCoreGettingStarted.Data;
using EFCoreGettingStarted.Models;
var builder = WebApplication.CreateBuilder(args); // For ASP.NET Core, or use plain C# for console
// For a console application, you might set up DbContextOptions manually
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
// Use SQLite for simplicity in this example, but SQL Server is common
// For SQL Server: optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=BloggingEFCore;Trusted_Connection=True;");
optionsBuilder.UseSqlite("Data Source=blogging.db"); // Using SQLite for this console example
using (var context = new BloggingContext(optionsBuilder.Options))
{
// Ensure the database is created (in-memory or file-based)
context.Database.EnsureCreated();
// Example: Add a new blog
var newBlog = new Blog { Url = "http://example.com" };
context.Blogs.Add(newBlog);
context.SaveChanges();
Console.WriteLine($"Added blog with ID: {newBlog.BlogId}");
// Example: Query blogs
Console.WriteLine("Blogs:");
foreach (var blog in context.Blogs)
{
Console.WriteLine($"- {blog.Url}");
}
}
Console.WriteLine("EF Core setup complete.");
Step 6: Migrations (Recommended for Production)
Migrations are EF Core's way of incrementally evolving your database schema as your application models change. They are crucial for managing database changes in development and production environments.
First, ensure you have installed the tools package and are in your project directory:
dotnet add package Microsoft.EntityFrameworkCore.Design
Then, create your first migration:
dotnet ef migrations add InitialCreate
This command will generate code that creates your database schema based on your DbContext and models.
To apply the migration to your database:
dotnet ef database update
Important: For actual production applications, use a robust connection string and consider using tools like EF Core Power Tools or command-line arguments for more advanced migration management.
Next Steps
You've successfully set up EF Core and performed basic operations. From here, you can explore more advanced topics:
- EF Core Migrations for managing schema changes.
- Querying Data with LINQ.
- Advanced Topics like change tracking, relationships, and performance tuning.