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:

Key Features

Getting Started with EF Core

To get started with EF Core, you'll typically need to:

  1. Install the necessary EF Core NuGet packages.
  2. Define your domain entities (POCO classes).
  3. Define a DbContext class that represents a session with the database.
  4. Configure your database provider (e.g., SQL Server, SQLite, PostgreSQL).
  5. 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.

Further Reading