Entity Framework

Entity Framework (EF) is a set of data access technologies developed by Microsoft that enables developers to program against relational databases. It is an Object-Relational Mapper (ORM) that allows developers to work with data using .NET objects, rather than SQL queries. This simplifies database interactions and improves developer productivity.

Key Concepts of Entity Framework

1. Object-Relational Mapping (ORM)

At its core, EF provides a way to map your .NET objects to database tables. This means you can define your data models as C# or VB.NET classes, and EF will handle the translation between these objects and the underlying database schema.

2. DbContext

The DbContext class is the primary gateway to interact with the database. It represents a session with the database and is used to query and save data. You typically create an instance of DbContext to perform database operations.


using System.Data.Entity;

public class MyDatabaseContext : DbContext
{
    public DbSet Products { get; set; }
    public DbSet Categories { get; set; }
}

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
}
                

3. DbSet

A DbSet<TEntity> represents a collection of a given entity type in the context. It provides methods for querying and manipulating the entities of that type. For example, context.Products would be a DbSet<Product>.

4. Migrations

EF Migrations is a feature that allows you to evolve your database schema over time as your application's data model changes. It provides a code-based approach to managing database schema changes, making it easier to deploy updates to your database.

5. Querying Data

EF integrates with Language Integrated Query (LINQ) to provide a powerful and expressive way to query your data. You can write LINQ queries that are translated into efficient SQL statements by EF.

Example LINQ Query:


using (var context = new MyDatabaseContext())
{
    var affordableProducts = context.Products
                                .Where(p => p.Price < 50.0m)
                                .OrderBy(p => p.Name)
                                .ToList();

    foreach (var product in affordableProducts)
    {
        Console.WriteLine($"{product.Name} - ${product.Price}");
    }
}
                

6. Saving Data

Adding, updating, or deleting entities is straightforward. You simply modify the objects in memory, and then call SaveChanges() on the DbContext to persist those changes to the database.

Example Saving Data:


using (var context = new MyDatabaseContext())
{
    // Add new product
    var newProduct = new Product { Name = "Wireless Mouse", Price = 25.99m };
    context.Products.Add(newProduct);

    // Update existing product
    var productToUpdate = context.Products.Find(1);
    if (productToUpdate != null)
    {
        productToUpdate.Price = 27.50m;
    }

    // Delete product
    var productToDelete = context.Products.Find(2);
    if (productToDelete != null)
    {
        context.Products.Remove(productToDelete);
    }

    context.SaveChanges();
}
                

EF Core vs. EF6

Entity Framework has evolved over time. EF Core is the latest generation of Entity Framework, a cross-platform, open-source, and high-performance version of the original Entity Framework. EF6 is the last major release of the original, Windows-only framework. For new development, EF Core is generally recommended.

EF simplifies data access by allowing you to treat your database as a collection of objects, enhancing productivity and maintainability.

Further Reading