22
DecDbContext in ASP.NET Core Explained: A Developer’s Guide
DBContext in ASP.NET Core: Entity Framework
A DbContext's lifetime starts at the moment of creation and ends when it is disposed of. The purpose of a DbContext instance is to support a single unit of work. This indicates that a DbContext instance's lifetime is typically quite brief.
In this EF Tutorial, we will explore more about dbContext which will include entity framework DB context example, Benefits of Using DbContext, etc, Let's see this concept in depth.
What is DBContext?
- DbContext is the main class in the.NET Core domain that is in charge of communicating with the database via Entity Framework Core.
- You can query and store data using it as a bridge between your domain or entity classes and the database.
- It includes methods to control the lifespan of the entities and all the configurations required to connect to a database.
Benefits of Using DbContext in Asp.net Core
Including DbContext in your ASP.NET Core application has lots of benefits.
- Simplified Data Access: By abstracting the database activities, DbContext makes it simpler to use LINQ queries rather than plain SQL to interface with your database.
- Change tracking: It enhances efficiency by automatically keeping track of changes made to your entities and letting you save just the modified versions.
- Transaction: Data integrity is ensured via DbContext's smooth handling of database transactions.
- Model Validation: It lowers runtime errors by validating data models against the database structure.
DbContext in Entity Framework Core
- A cross-platform, lightweight, and flexible variant of the well-known Entity Framework data access technology is called Entity Framework Core (EF Core).
- A major component of EF Core is DbContext, which offers the framework for all database interactions.
Configure Database Connection
- In the Startup.cs file, you must set up the database connection in order to use DbContext in your ASP.NET Core application.
- This entails configuring the DbContext using the dependency injection system and putting up a connection string.
Let's see the step-by-step configuration
Step 1: Defining the Connection String
Define your database's connection string in your appsettings.json file:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=CompanyDatabase;Trusted_Connection=True;"
}
}
Step 2:DbContext configuration in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllersWithViews();
}
The Link Between the Database and Your Application
- DbContext serves as an intermediary between the database and your application.
- It offers ways to query and save data, mapping your domain classes to the database tables.
- In addition, it maintains the database connection and guarantees effective database communication.
Your Entry Point for Database Communication
- You may execute a number of database actions, including inserting, updating, removing, and querying data, using DbContext.
- It enables you to build strongly typed queries using LINQ (Language Integrated Query).
Example
Here's an example of a DbContext data query:
public class MyApp
{
private readonly MyDbContext _context;
public MyApp(MyDbContext context)
{
_context = context;
}
public async Task> GetProductsAsync()
{
return await _context.Products.ToListAsync();
}
}
Simplifying Entity Framework Data Access
- By giving a higher-level abstraction over database processes, DbContext streamlines data access.
- LINQ allows you to conduct operations in a more legible and manageable manner than writing raw SQL queries.
A Core Concept for Using Entity Framework Core
- It is essential to use DbContext properly when utilizing Entity Framework Core.
- It serves as the cornerstone around which your database activities revolve and is essential to maintaining the effectiveness, security, and maintainability of your data access layer.
Common DbContext Operations
1. Add Data
var employee= new Employee{ Name = "New Employee" };
_context.Employees.Add(employee);
await _context.SaveChangesAsync();
2. Update Data
var employee= await _context.Products.FindAsync(id);
if (employee != null)
{
employee.Name = "Updated Employee Name";
await _context.SaveChangesAsync();
}
3. Delete Data
var employee= await _context.Employees.FindAsync(id);
if (employee != null)
{
_context.Employees.Remove(employee);
await _context.SaveChangesAsync();
}