Entity Framework Core APIs

Explore the core APIs and functionalities of Entity Framework Core, Microsoft's modern object-relational mapper (ORM) for .NET.

Core Concepts

Entity Framework Core (EF Core) allows developers to work with databases using .NET objects, eliminating the need for most of the data-access code that developers traditionally need to write.

Key API Categories

DbContext

The central class in EF Core, representing a session with the database and allowing you to query and save data.

DbContext(DbContextOptions options) Initializes a new instance of the DbContext class.
DbSet<TEntity> Set<TEntity>() Returns a DbSet<TEntity> representing a collection of objects for the given entity type.
int SaveChanges() Saves all changes made in this context to the database.
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default) Asynchronously saves all changes made in this context to the database.

DbSet<TEntity>

Represents a collection of all entities in the context, or that can be queried from the database, of a given type.

IQueryable<TEntity> AsQueryable() Returns a IQueryable<TEntity> representing the entity set.
TEntity Add(TEntity entity) Adds a new entity to the context.
EntityState Entry(object entity).State Gets or sets the EntityState for a given entity.

Model Building

Configure your entity models and relationships using the OnModelCreating method.

protected override void OnModelCreating(ModelBuilder modelBuilder) Override this method to configure the entity models and relationships.
modelBuilder.Entity<TEntity>().HasKey(e => e.Id) Configures the primary key for an entity.
modelBuilder.Entity<TEntity>().HasOne<TNavigation>(e => e.Navigation) Configures a one-to-one or one-to-many relationship.

Migrations

Manage database schema changes over time.

Add-Migration <Name> Creates a new migration from current model changes. (Package Manager Console)
dotnet ef migrations add <Name> Creates a new migration from current model changes. (.NET CLI)
Update-Database Updates the database to the latest migration. (Package Manager Console)
dotnet ef database update Updates the database to the latest migration. (.NET CLI)

For more detailed information and examples, please refer to the official Entity Framework Core documentation.

Further Resources: