Introduction to Entity Framework

Entity Framework (EF) is an object-relational mapper (ORM) that enables developers to work with relational data using domain-specific objects instead of the data structures typically manipulated by database programming techniques. It eliminates the need for most of the data-access code that developers traditionally need to write.

EF is an open-source, extensible, and cross-platform data access technology for .NET developers. It allows developers to query and save data in the form of strongly-typed objects, rather than through ADO.NET constructs like DataReader and DataSet.

Key Concepts

Why Use Entity Framework?

EF Core vs. EF6

Entity Framework has evolved over time. Entity Framework Core (EF Core) is the latest, cross-platform, open-source version. Entity Framework 6 (EF6) is the last version of the original framework. While EF6 is still supported, EF Core is recommended for new development due to its performance improvements, new features, and broader platform support.

Note: This documentation primarily focuses on Entity Framework Core. For details on EF6, please refer to the EF6 documentation archive.

Getting Started with EF Core

To start using EF Core, you'll typically:

  1. Install the necessary EF Core NuGet packages.
  2. Define your entity classes.
  3. Create a DbContext class that represents a session with your database.
  4. Configure your database connection and model mappings (often through convention or explicit configuration).
  5. Use the DbContext to query and save data.

Here's a minimal example of a DbContext and an entity:


public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public virtual 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 virtual Blog Blog { get; set; }
}

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=BloggingEFCore;Trusted_Connection=True;");
    }
}
            

This introduction provides a foundational understanding of Entity Framework. Subsequent sections will delve deeper into specific approaches like Code-First, Database-First, and Model-First, as well as essential features like LINQ to Entities and Migrations.