03_DbContext - Maniconserve/EF-Core GitHub Wiki
- The DbContext class is part of the Microsoft.EntityFrameworkCore package.
- It acts as a bridge between the database and the application.
- It manages database operations like querying, inserting, updating, and deleting records.
Common Methods in DbContext
Add(entity) – Adds a new record to the database.
AddRange(entities) – Adds multiple records at once.
Find(key) – Retrieves an entity by primary key.
FirstOrDefault() – Returns the first matching record or null if none found.
Update(entity) – Updates an existing record.
Remove(entity) – Deletes a record from the database.
SaveChanges() – Commits all changes to the database.
SaveChangesAsync() – Asynchronously commits changes to the database.
Set() – Gets the DbSet for a specific entity type.
Entry(entity) – Provides access to entity tracking information.
1. Constructor Injection in DbContext
- Uses dependency injection to provide the DbContextOptions at runtime.
- Recommended for ASP.NET Core applications to manage the DbContext through DI container.
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Employee> Employees { get; set; }
}
- The DbContext is registered in Program.cs:
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
- OnConfiguring Method in DbContext
- Used when dependency injection is not available.
- Manually configures the database connection inside DbContext.
public class ApplicationDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=.;Database=MyDB;Trusted_Connection=True;");
}
public DbSet<Employee> Employees { get; set; }
}
- This method directly sets the connection string, useful in small applications or console applications without dependency injection.