Entity Framework API Reference
This section provides a comprehensive reference to the core APIs available in Entity Framework (EF) for .NET. Explore classes, methods, properties, and their usage to leverage EF effectively in your applications.
Core Namespaces
Entity Framework's functionality is organized across several key namespaces. Understanding these namespaces is crucial for navigating the API.
Microsoft.EntityFrameworkCore
Namespace
This is the primary namespace for EF Core. It contains the most frequently used classes and interfaces for interacting with your data context, entities, and querying.
DbContext
: The central class that represents a session with the database and can be used to query and save data.DbSet<TEntity>
: Represents a collection of entities of a particular type in the context, which can be used for querying and saving operations.ModelBuilder
: Used to configure the EF Core model.SaveChangesOptions
: Options for theSaveChanges
operation.
Microsoft.EntityFrameworkCore.Metadata
Namespace
This namespace deals with the EF Core model's metadata, allowing for inspection and programmatic configuration of entities, properties, and relationships.
IModel
: Represents the EF Core model.IEntityType
: Represents an entity type in the model.IProperty
: Represents a property of an entity type.
Microsoft.EntityFrameworkCore.Query
Namespace
Contains classes related to query construction and execution.
IQueryable<T>
: Represents a LINQ query.Expression
: Represents an operation that can be executed.
Key Classes and Their Methods
DbContext
The foundation of your interaction with EF Core.
public abstract class DbContext : IDisposable
{
public DbContext();
public DbContext(DbContextOptions options);
public DbSets...
public int SaveChanges(bool acceptAllChangesOnSuccess = true);
public Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess = true, CancellationToken cancellationToken = default);
public void Dispose();
public Task DisposeAsync();
// ... other methods
}
DbSet<TEntity>
Used to access and manipulate collections of entities.
public class DbSet<TEntity> : IQueryable<TEntity>, IEnumerable<TEntity>, IAsyncEnumerable<TEntity> where TEntity : class
{
public EntityState State { get; set; }
public void Add(TEntity entity);
public void AddRange(IEnumerable<TEntity> entities);
public Task AddRangeAsync(IEnumerable<TEntity> entities, CancellationToken cancellationToken = default);
public void Remove(TEntity entity);
public void RemoveRange(IEnumerable<TEntity> entities);
public void Update(TEntity entity);
public void UpdateRange(IEnumerable<TEntity> entities);
// ... other methods
}
ModelBuilder
Configures the EF Core model at runtime or design time.
public class ModelBuilder
{
public ModelBuilder Entity<TEntity>() where TEntity : class;
public ModelBuilder Ignore<TEntity>() where TEntity : class;
public ModelBuilder ApplyConfiguration<TEntity>(IEntityTypeConfiguration<TEntity> configuration) where TEntity : class;
// ... other methods for configuring properties, relationships, etc.
}
Common Operations and API Usage
Creating a DbContext
Instance
Typically done using dependency injection or by passing options.
// Using dependency injection
public class MyController : Controller
{
private readonly ApplicationDbContext _context;
public MyController(ApplicationDbContext context)
{
_context = context;
}
// ...
}
// Manually creating an instance
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlServer("YourConnectionString");
var context = new ApplicationDbContext(optionsBuilder.Options);
Querying Data
Leverage LINQ to query your data.
// Get all blogs
var blogs = await _context.Blogs.ToListAsync();
// Get a specific blog by ID
var blog = await _context.Blogs.FindAsync(1);
// Query with filtering and ordering
var popularPosts = await _context.Posts
.Where(p => p.Likes > 100)
.OrderByDescending(p => p.CreatedAt)
.ToListAsync();
Saving Data
Add, update, or remove entities and then call SaveChanges
.
// Add a new blog
var newBlog = new Blog { Url = "https://example.com", Rating = 5 };
_context.Blogs.Add(newBlog);
await _context.SaveChangesAsync();
// Update an existing blog
var blogToUpdate = await _context.Blogs.FindAsync(1);
if (blogToUpdate != null)
{
blogToUpdate.Rating = 4;
_context.Blogs.Update(blogToUpdate); // Optional if tracking is enabled
await _context.SaveChangesAsync();
}
// Remove a blog
var blogToRemove = await _context.Blogs.FindAsync(2);
if (blogToRemove != null)
{
_context.Blogs.Remove(blogToRemove);
await _context.SaveChangesAsync();
}