Entity Framework Overview

Entity Framework (EF) is a set of technologies in the .NET Framework that supports the development of ASP.NET applications that use enterprise-level data, such as organizational data, that exists in relational databases.

EF enables developers to work with data in object-oriented classes. This means that developers can interact with the data in their applications using the same .NET Framework objects they typically use to interact with other data, such as business objects.

Key Benefit: EF abstracts away the need for much of the data-access code that developers typically need to write. This significantly speeds up development time and reduces the complexity of data access logic.

What is Entity Framework?

Entity Framework is an Object-Relational Mapper (ORM). It provides an abstraction layer over a relational database, allowing developers to interact with the database using .NET objects instead of writing raw SQL queries.

With EF, you can:

  • Query: Retrieve data from your database using LINQ (Language Integrated Query) syntax, which feels natural to C# and Visual Basic developers.
  • Track Changes: EF automatically tracks changes made to your objects.
  • Save Changes: EF translates these changes into SQL commands and executes them against the database.
  • Model First, Database First, and Code First: EF supports various development approaches, allowing you to define your data model from a database, from a conceptual model, or directly in your code.

Core Concepts

1. DbContext

The DbContext class is the primary gateway to interacting with the EF data store. It represents a session with the database and can be used to query and save data. You typically create an instance of your derived context class and then access it through properties that represent collections of entities in the store.


using System.Data.Entity;

public class BlogContext : DbContext
{
    public DbSet<Post> Posts { get; set; }
    public DbSet<User> Users { get; set; }
}
                

2. DbSet

A DbSet<TEntity> represents a collection of a given entity type in the context, which can be used for reading and writing data. It is conceptually similar to a table in a database.

3. Entities

Entities are .NET objects that represent data in your database. These are typically simple Plain Old CLR Objects (POCOs) that correspond to tables or views in your database.

Tip: Using POCOs makes your domain logic more reusable and decouples it from the data access layer.

Common Scenarios

Querying Data

You can use LINQ to query your entities directly through the DbContext.


using (var context = new BlogContext())
{
    var recentPosts = context.Posts
                             .Where(p => p.PublishedDate > DateTime.Now.AddDays(-7))
                             .OrderByDescending(p => p.PublishedDate)
                             .ToList();

    foreach (var post in recentPosts)
    {
        Console.WriteLine(post.Title);
    }
}
                

Adding and Saving Data

To add a new entity, you simply add it to the appropriate DbSet and then call SaveChanges() on the context.


var newPost = new Post
{
    Title = "Introduction to EF Core",
    Content = "Entity Framework Core is a modern...",
    PublishedDate = DateTime.Now
};

using (var context = new BlogContext())
{
    context.Posts.Add(newPost);
    context.SaveChanges(); // This executes the INSERT statement.
}
                

Updating Data

To update an entity, retrieve it, modify its properties, and then call SaveChanges().


using (var context = new BlogContext())
{
    var postToUpdate = context.Posts.Find(1); // Assuming 1 is the ID of the post.
    if (postToUpdate != null)
    {
        postToUpdate.Content = "Updated content for the post...";
        context.SaveChanges(); // This executes the UPDATE statement.
    }
}
                

Deleting Data

To delete an entity, retrieve it, mark it for deletion, and then call SaveChanges().


using (var context = new BlogContext())
{
    var postToDelete = context.Posts.Find(2); // Assuming 2 is the ID of the post.
    if (postToDelete != null)
    {
        context.Posts.Remove(postToDelete);
        context.SaveChanges(); // This executes the DELETE statement.
    }
}
                

Entity Framework Core vs. EF6

Entity Framework Core is the latest version of Entity Framework, which has been completely rewritten and is a lighter-weight and more extensible version. EF6 is the last version of Entity Framework that runs on the .NET Framework.

Key differences include:

  • Performance: EF Core generally offers better performance.
  • Cross-Platform: EF Core is cross-platform and runs on Windows, macOS, and Linux.
  • Extensibility: EF Core is designed with extensibility in mind.
  • Feature Parity: While EF Core has reached feature parity with EF6 in many areas, some older features might be missing or implemented differently.

For new projects, it is highly recommended to use Entity Framework Core.

Next Steps

To dive deeper into Entity Framework: