Entity Framework DBContext

Entity Framework DBContext

30 May 2024
Beginner
111 Views
6 min read
Learn via Video Course & by Doing Hands-on Labs

ASP.NET Core Course

DBContext: 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

Including DbContext in your ASP.NET Core application has lots of benefits.

  1. 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.
  2. Change tracking: It enhances efficiency by automatically keeping track of changes made to your entities and letting you save just the modified versions.
  3. Transaction: Data integrity is ensured via DbContext's smooth handling of database transactions.
  4. Model Validation: It lowers runtime errors by validating data models against the database structure.

Benefits of Using DbContext

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:

Configure the DbContext in the ConfigureServices function of the Startup.cs file:
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();
}    
Conclusion
An effective and fast approach for interacting with your database in ASP.NET Core apps is through DbContext, It is an effective and essential part of Entity Framework Core. I hope you find this article informative. Your valuable feedback or comments about this Entity framework article are always welcome. If you are preparing for an interview go through this Top 50 Entity Framework Interview Questions & Answers.

FAQs

Q1. What is DbContext used for?

It is used to query and save instances of your entities.

Q2. What is DbSet and DbContext in Entity Framework?

A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext.

Q3. How to define DbContext?

It defines a class that derives from DbContext and exposes DbSet properties that represent collections of the specified entities in the context.
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Certification Training Jul 06 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
ASP.NET Core Certification Training Jul 15 MON, WED, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
Azure Developer Certification Training Jul 21 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Software Architecture and Design Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this