Entity Framework Core
Entity Framework Core (EF Core) is a modern, cross-platform, extensible object-relational mapper (ORM) for .NET. It enables .NET developers to work with a database using .NET objects that map to the database tables. It eliminates the need for most of the data-access code that developers typically need to write.
What is Entity Framework Core?
EF Core provides a set of APIs for:
- Defining a data model: You can define your database schema using .NET classes and attributes, or by using code-first conventions.
- Querying data: EF Core translates LINQ queries into SQL queries that are executed against the database.
- Saving data: You can add, update, and delete entities, and EF Core will generate the appropriate SQL commands to persist these changes to the database.
- Managing database schema: EF Core Migrations allows you to evolve your database schema over time as your application's model changes.
Key Features
- Cross-platform: Works on Windows, macOS, and Linux.
- LINQ support: Allows you to write queries using Language Integrated Query (LINQ).
- Change tracking: EF Core tracks changes to your entities to efficiently generate SQL updates.
- Connection resiliency: Built-in retry logic for transient database errors.
- T4 Templating: Supports custom code generation for models and contexts.
- Extensibility: Designed with extensibility in mind, allowing for custom providers and interceptors.
Getting Started with EF Core
To get started with EF Core, you'll typically need to:
- Install the necessary EF Core NuGet packages.
- Define your domain entities (POCO classes).
- Define a
DbContext
class that represents a session with the database. - Configure your database provider (e.g., SQL Server, SQLite, PostgreSQL).
- Use the
DbContext
to query and save data.
Example: Defining a Model
Here's a simple example of defining a Blog
entity:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<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 Blog Blog { get; set; }
}
Example: Defining a DbContext
And a corresponding DbContext
:
using Microsoft.EntityFrameworkCore;
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Blogging;Trusted_Connection=True;");
}
}
Important Note
For production scenarios, it is highly recommended to configure your DbContext
using dependency injection and configuration providers rather than hardcoding connection strings in OnConfiguring
.