IT Education

DbContext Class in Entity Framework 6 DB-First Approach

Let’s use the EnsureCreated() method to create a database and use the context class to save student and grade data in the database. According to MSDN, an instance of DbContext represents a session with the database and can be used to query and save instances of your entities. DbContext is a combination of the Unit of Work and Repository patterns. A third option is to create a DbContext instance by overriding the OnConfiguring method in your custom DbContext class. You can then take advantage of the DbContext constructor to pass configuration information, such as a connection string. The Database instance manages the connection to the database, transactions and all other database related operations.

what is dbcontext in entity framework

This list documents EF’s behaviour when working against SQL Server. Here are a few points that I would consider to be essential for most applications. When coming up with or evaluating a DbContext lifetime management strategy, it’s important to keep in mind the key scenarios and functionalities that it must support. The optionsBuilder.IsConfigured returns a boolean value indicating whether any options have been configured.

There’s no built-in way to override the default isolation level used for AutoCommit and automatic explicit transactions

The DbEntityEntry provides information about the entity and also has the ability to perform actions on the entity. The Correct way to use DbContext in our application is by creating a class and deriving from the DbContext. The entities existing in the project can be exposed using the DbSet Property. Anyway, here you’ll find a very simple Visual Studio template that uses the Repository Pattern and the Entity Framework. Tutorials Point is a leading Ed Tech company striving to provide the best learning material on technical and non-technical subjects.

what is dbcontext in entity framework

A DbContext instance should be disposed when it is no longer needed to free up any unmanaged resources and prevent memory leaks. However, it is not a recommended practice to dispose off DbContext instances explicitly or to use DbContext within a using statement. The context Provides automatic validation of data at the data layer. This API makes use of the validation features already built in .NET Framework.


A DbContext instance can however span across multiple (sequential) business transactions. Once a business transaction has completed and has called the DbContext.SaveChanges() method to persist all the changes it made, it’s entirely possible to just re-use the same DbContext instance for what is entity framework the next business transaction. So, in the next article, I will discuss where to define the Connection String in Entity Framework Core and how to use it to interact with the SQL Server Database. In this article, I explain the need and use of the DbContext Class in Entity Framework Core.

Here, in this article, I try to explain the DbContext Class in Entity Framework Database First Approach and I hope you enjoyed DbContext class in the Entity Framework article. Please give your valuable feedback and suggestions about this article. In this case, you can use the AddDbContextFactory method to register a factory and create your DbContext objects as shown in the code snippet given below.

DbContext is not thread-safe

It returns a Collection of DbEntityValidationResult containing validation results.

what is dbcontext in entity framework

The DbSet type allows EF Core to query and save instances of the specified entity to the database. LINQ queries against a DbSet will be translated into queries against the database. EF Core API will create the Student and Grade table in the underlying SQL Server database where each property of these classes will be a column in the corresponding table. The context class in Entity Framework is a class which derives from System.Data.Entity.DbContext in EF 6 and EF Core both.

Transaction Management

So you’re effectively back to the explicit DbContext approach discussed earlier. I can think of a few ways in which this could be solved but all of them feel more like hacks than clean and elegant solutions. This approach does however introduce a certain amount of magic which can certainly make the code more difficult to understand and maintain. When looking at the data access code, it’s not necessarily easy to figure out where the ambient DbContext is coming from. You just have to hope that someone somehow registered it before calling the data access code.

So, create a class file within the Entities folder named Student.cs, and then copy and paste the following code. As you can see, here, we are creating the Student class with a few scalar properties and one Reference Navigation property called Standard, which makes the relationship between Student and Standard entities one-to-one. In the above example, when we deleted one existing student entity. Once we remove the entity, the entity will be moved to the Deleted state and when we call the SaveChanges method, the context object will generate and execute the following DELETE SQL statement. Once the SaveChanges method execution is completed successfully, it will move the Entity state from Deleted to Detached state and no longer be tracked by the context object. Now, we need to update one existing entity i.e. we need to update the First name and Last name of the newly created student i.e. the student whose student id is 5.

First, we need connection string , which can be obtained from the IConfiguration instance. So to put it the other way around, if you want to do data access with Entity Framework, DbContext is what you want. Now, we are done with the initial domain classes for our application. Later, as we progress, we will add more domain classes to this example. Using the Entity Framework DbContext class we can perform the database CRUD operations i.e.

what is dbcontext in entity framework

Its instances should therefore be disposed of as soon as they’re not needed anymore. As you can see by yourself by running the SQL script below, neither Autocommit nor Implicit transactions have any significant performance impact for SELECT statements. If you’re coming from an NHibernate background, the way Entity Framework persists changes to the database is one of the major differences between EF and NHibernate. Entity Framework’s async features are there to support an asynchronous programming model, not to enable parallelism.

What is the purpose of a db context class in mvc

As soon as you introduce stateful services, careful consideration has to be given to your service lifetimes. With this approach, you let your DI container manage the lifetime of your DbContext and inject it into whatever component needs it (your repository objects for example). NHibernate users will be very familiar with this approach as the ambient context pattern is the predominant approach used in the NHibernate world to manage NH’s Session (NHibernate’s equivalent to EF’s DbContext). NHibernate even comes with built-in support for this pattern, which it calls contextual sessions. Finally, managing your DbContext instance lifetime outside of your services tends to tie your application to a specific infrastructure, making it a lot less flexible and much more difficult to evolve and maintain in the long run. For many applications, the solutions presented in those articles (which generally revolve around using a DI container to inject DbContext instances with a PerWebRequest lifetime) will work just fine.

  • Perhaps the main source of confusion when it comes to managing DbContext instances is understanding the difference between the lifetime of a DbContext instance and the lifetime of a business transaction and how they relate.
  • DbContext exposes the property (DbSet) which represent collections of entities in the context.
  • The context Provides automatic validation of data at the data layer.
  • It will reuse the connections wherever possible and creates a new connection only when needed.
  • To use the code examples provided in this article, you should have Visual Studio 2022 installed in your system.

Leave a Reply

Your email address will not be published. Required fields are marked *