Getting Started with Entity Framework Core
This tutorial will guide you through the fundamental steps to start using Entity Framework Core (EF Core) in your .NET applications. We'll cover project setup, defining your data model, and performing basic data operations.
Prerequisites
- .NET SDK (version 6.0 or later recommended)
- A code editor (Visual Studio, VS Code, Rider)
- Basic understanding of C# and object-oriented programming
Step 1: Create a New Project
First, 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
You need to install the EF Core tools and the EF Core provider for your database. For this example, we'll use SQLite, which is lightweight and easy to set up.
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet tool install --global dotnet-ef --version 7.0.0
dotnet-ef
tool is used for scaffolding and migrations. Ensure you have a compatible version installed.
Step 3: Define Your Data Model
Let's define a simple model for a `Book` entity. Create a new folder named `Models` and add a `Book.cs` file inside it.
// Models/Book.cs
namespace EFCoreGettingStarted.Models
{
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public string Author { get; set; }
}
}
Step 4: Create Your DbContext
The DbContext
class represents a session with your database and allows you to query and save data. Create a `Data` folder and add a `ApplicationDbContext.cs` file.
// Data/ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
using EFCoreGettingStarted.Models;
namespace EFCoreGettingStarted.Data
{
public class ApplicationDbContext : DbContext
{
public DbSet<Book> Books { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// This is an example; consider externalizing connection strings.
optionsBuilder.UseSqlite("Data Source=books.db");
}
}
}
OnConfiguring
.
Step 5: Configure Services (Program.cs)
Modify your Program.cs
file to register your DbContext
with the .NET's built-in dependency injection container.
// Program.cs
using Microsoft.EntityFrameworkCore;
using EFCoreGettingStarted.Data;
using EFCoreGettingStarted.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
// Ensure database is created (for development/testing purposes)
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
// For this simple console app, we'll just ensure it exists.
// In web apps, migrations are preferred.
dbContext.Database.EnsureCreated();
}
Console.WriteLine("EF Core Getting Started!");
// --- Example Data Operations ---
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
// Add a new book
var newBook = new Book { Title = "The Lord of the Rings", Author = "J.R.R. Tolkien" };
dbContext.Books.Add(newBook);
await dbContext.SaveChangesAsync();
Console.WriteLine($"Added book: {newBook.Title}");
// Query books
var books = await dbContext.Books.ToListAsync();
Console.WriteLine("\n--- All Books ---");
foreach (var book in books)
{
Console.WriteLine($"- {book.Title} by {book.Author}");
}
// Find a specific book
var bookToFind = await dbContext.Books.FindAsync(newBook.BookId);
if (bookToFind != null)
{
Console.WriteLine($"\nFound book: {bookToFind.Title}");
// Update a book
bookToFind.Author = "John Ronald Reuel Tolkien";
await dbContext.SaveChangesAsync();
Console.WriteLine($"Updated author for: {bookToFind.Title}");
}
// Delete a book
var bookToDelete = await dbContext.Books.FirstOrDefaultAsync(b => b.Title == "The Lord of the Rings");
if (bookToDelete != null)
{
dbContext.Books.Remove(bookToDelete);
await dbContext.SaveChangesAsync();
Console.WriteLine($"\nDeleted book: {bookToDelete.Title}");
}
}
app.Run();
Database.EnsureCreated()
.
Step 6: Run the Application
Now, run your console application from the terminal:
dotnet run
You should see output indicating that the database was created, books were added, queried, updated, and deleted.
Conclusion
Congratulations! You've successfully set up Entity Framework Core, defined a data model, and performed basic CRUD (Create, Read, Update, Delete) operations. This is just the beginning of what you can achieve with EF Core. Explore the official EF Core documentation for more advanced features like relationships, performance tuning, and complex querying.