Getting Started with Entity Framework Core
Entity Framework Core (EF Core) is a modern, cross-platform, and extensible version of the familiar Entity Framework data access technology.
What is Entity Framework Core?
EF Core enables .NET developers to work with a database using an object-oriented programming style. It eliminates the need for most of the data-access code that developers traditionally need to write.
Key features include:
- LINQ to Entities: Query your database using Language Integrated Query (LINQ).
- Change Tracking: EF Core automatically tracks changes made to entities.
- Database Providers: Support for various database systems like SQL Server, SQLite, PostgreSQL, MySQL, Oracle, and more.
- Migrations: Manage database schema changes over time.
- Performance Optimizations: Designed for performance and efficiency.
Installation
You can install EF Core using the .NET CLI or the NuGet Package Manager in Visual Studio.
Using .NET CLI
To add the EF Core tools and a database provider (e.g., for SQL Server), run the following commands in your project directory:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
Using NuGet Package Manager
In Visual Studio, right-click on your project in Solution Explorer, select "Manage NuGet Packages...", search for Microsoft.EntityFrameworkCore and your desired database provider (e.g., Microsoft.EntityFrameworkCore.SqlServer), and click "Install".
Creating Your First EF Core Model
An EF Core model is defined by your C# classes, often referred to as Plain Old CLR Objects (POCOs).
Example: A Simple Blog Model
Let's define a simple model for a blog application:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public virtual ICollection<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 virtual Blog Blog { get; set; }
}
EF Core uses conventions to map these classes to database tables and columns. For example, a property named BlogId is automatically recognized as a foreign key relationship.
Creating a `DbContext`
The DbContext class represents a session with the database and allows you to query and save data. It's the bridge between your domain model and the database.
Example: `BloggingContext`
Create a class that inherits from DbContext:
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 model using Fluent API
modelBuilder.Entity<Blog>().Property(b => b.Url).IsRequired().HasMaxLength(200);
modelBuilder.Entity<Post>().Property(p => p.Title).IsRequired().HasMaxLength(100);
}
}
The DbSet<TEntity> properties represent collections of entities in the context. They will typically be mapped to database tables.
DbContext with your dependency injection container (e.g., in Startup.cs or Program.cs in .NET 6+).
Configuring the Database Connection
You need to tell EF Core which database to use and how to connect to it. This is typically done in your application's startup configuration.
Example: Using SQL Server (in Program.cs for .NET 6+)
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
// Configure DbContext with SQL Server
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<BloggingContext>(options =>
options.UseSqlServer(connectionString));
var app = builder.Build();
// ... rest of your app configuration
Your appsettings.json should contain the connection string:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=BloggingDB;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
Next Steps
Now that you have EF Core set up, you can start querying and saving data. The next logical steps are: