Entity Framework Core
Getting Started with Entity Framework Core
Entity Framework Core (EF Core) is a modern, cross-platform, extensible data access technology for .NET. It is a rewrite of the popular Entity Framework data access technology.
What is Entity Framework Core?
EF Core allows .NET developers to work with databases using .NET objects. It simplifies data access by providing an object-relational mapper (ORM) that maps database tables to C# classes and database rows to C# objects. This abstraction layer significantly reduces the amount of boilerplate data access code you need to write.
Key Features
- Cross-Platform: Runs on Windows, macOS, and Linux.
- Modern and Extensible: Designed with extensibility in mind, allowing for custom providers and features.
- Performance Improvements: Significant performance enhancements over previous versions of Entity Framework.
- LINQ Support: Powerful querying capabilities using Language Integrated Query (LINQ).
- Migrations: Tools for managing database schema changes over time.
- Multiple Database Providers: Supports a wide range of databases including SQL Server, SQLite, PostgreSQL, MySQL, Azure Cosmos DB, and more.
Installation
To start using EF Core, you need to install the appropriate NuGet packages for your project. The core package is Microsoft.EntityFrameworkCore
.
Package Manager Console:
Install-Package Microsoft.EntityFrameworkCore
.NET CLI:
dotnet add package Microsoft.EntityFrameworkCore
You will also need to install a database provider. For example, to use SQL Server:
Package Manager Console:
Install-Package Microsoft.EntityFrameworkCore.SqlServer
.NET CLI:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
Setting up a DbContext
The central piece of EF Core is the DbContext
class. This class represents a session with the database and can be used to query and save data. You typically create a class that inherits from DbContext
and define DbSet<TEntity>
properties for each entity in your domain model that you want to persist.
Note: The DbContext
is designed to be a short-lived object. It should be created, used to execute operations, and then disposed.
Here's an example of a simple 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 relationships, constraints, etc.
modelBuilder.Entity<Blog>().Property(b => b.Url).IsRequired();
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public ICollection<Post> Posts { get; } = new List<Post>();
}
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; }
}
Configuring the DbContext
You need to configure the DbContext
to use a specific database provider and connection string. This is typically done in your application's startup or configuration code, often using dependency injection.
Example using Dependency Injection (e.g., in ASP.NET Core):
// In Startup.cs or Program.cs
services.AddDbContext<BloggingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
And in your appsettings.json
:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=BloggingEFCore;Trusted_Connection=True;"
}
}
Performing CRUD Operations
Once your DbContext
is set up, you can perform common database operations:
Creating Data
using var context = new BloggingContext(); // Or inject via DI
var blog = new Blog { Url = "http://blogs.msdn.microsoft.com/ef" };
context.Blogs.Add(blog);
await context.SaveChangesAsync();
Reading Data
using var context = new BloggingContext();
var blogs = await context.Blogs.ToListAsync();
// Or query with LINQ
var efCoreBlog = await context.Blogs
.Where(b => b.Url.Contains("efcore"))
.FirstOrDefaultAsync();
Updating Data
using var context = new BloggingContext();
var blogToUpdate = await context.Blogs.FindAsync(1);
if (blogToUpdate != null)
{
blogToUpdate.Url = "https://devblogs.microsoft.com/dotnet";
await context.SaveChangesAsync();
}
Deleting Data
using var context = new BloggingContext();
var blogToDelete = await context.Blogs.FindAsync(1);
if (blogToDelete != null)
{
context.Blogs.Remove(blogToDelete);
await context.SaveChangesAsync();
}
Tip: Always remember to call await context.SaveChangesAsync();
after making changes to persist them to the database.