Entity Framework APIs

Explore the core APIs and classes for working with Entity Framework in .NET.

Introduction to Entity Framework

Entity Framework (EF) is a lightweight, extensible, and open-source object-relational mapper (ORM) for .NET. It enables developers to work with a database using .NET objects, eliminating the need for most of the data-access code they typically need to write.

This documentation provides an in-depth look at the various APIs and classes that comprise Entity Framework, covering everything from basic model creation to advanced query techniques.

Core Concepts and APIs

DbContext

The DbContext class is the primary gateway to interacting with your data. It represents a session with the database and provides access to entities.

Key Properties and Methods:

DbSet Set()
Gets a DbSet instance for the given entity type. This method is typically called from a derived context instance.
int SaveChanges()
Saves all changes made in this context to the underlying database. Returns the number of states of the entries that were successfully saved.
Task SaveChangesAsync(CancellationToken cancellationToken = default)
Asynchronously saves all changes made in this context to the underlying database.
void Dispose()
Disposes of the context instance.

Example:


using (var context = new MyDbContext())
{
    var blogs = context.Blogs
        .Where(b => b.Rating > 3)
        .OrderBy(b => b.Url)
        .ToList();

    var newBlog = new Blog { Url = "http://example.com", Rating = 5 };
    context.Blogs.Add(newBlog);
    context.SaveChanges();
}
                        

DbSet

A DbSet represents a collection of all entities in the store for a given entity type. DbSet can be used to query and save data for a particular entity.

Common Operations:

Add(TEntity entity)
Adds an entity to the context and marks it as Added. Will be inserted into the database when SaveChanges is called.
Remove(TEntity entity)
Removes an entity from the context and marks it as Deleted. Will be deleted from the database when SaveChanges is called.
Update(TEntity entity)
Updates an entity in the context and marks it as Modified. Will be updated in the database when SaveChanges is called.
Find(params object[] keyValues)
Finds an entity with the given primary key value(s). If the entity is found in the context already, it is returned without a database query.

Example:


var post = new Post { Title = "New Article", Content = "Content here..." };
context.Posts.Add(post);
context.SaveChanges();

var loadedPost = context.Posts.Find(post.Id);
if (loadedPost != null)
{
    context.Posts.Remove(loadedPost);
    context.SaveChanges();
}
                        

EntityState

The EntityState enum represents the current state of an entity within the DbContext.

States:

  • Detached: The entity is not being tracked by the context.
  • Unchanged: The entity has not been modified since it was attached to the context.
  • Added: The entity has been added to the context and has not yet been saved to the database.
  • Deleted: The entity has been marked for deletion from the database.
  • Modified: The entity has been modified since it was attached to the context.
  • Unknown: The state of the entity is unknown.

You can manually set the state of an entity:


context.Entry(blog).State = EntityState.Modified;
context.SaveChanges();
                        

Querying Data

Entity Framework provides powerful LINQ-based querying capabilities.

LINQ to Entities

Use LINQ queries directly against your DbSet properties on your DbContext.

Example: Filtering and Projection


var query = from c in context.Customers
            where c.Country == "USA"
            select new { c.Name, c.City };

var results = query.ToList();
                        

Eager, Lazy, and Explicit Loading

Control how related entities are loaded to optimize performance.

  • Eager Loading: Load related data along with the main entities using Include().
  • Lazy Loading: Related entities are loaded automatically when accessed (requires virtual navigation properties).
  • Explicit Loading: Load related data on demand using Load() or LoadAsync().

Example: Eager Loading


var orders = context.Orders
    .Include(o => o.Customer)
    .Include(o => o.OrderItems)
        .ThenInclude(oi => oi.Product)
    .ToList();
                        

Migrations

Migrations allow you to evolve your database schema over time as your application model changes.

  • Use the EF Core tools (CLI or Package Manager Console) to add and apply migrations.
  • Add-Migration InitialCreate
  • Update-Database