Digging much deeper into DbContext in Entity Framework Core


Entity Structure Core is an object-relational mapper, or ORM, that isolates your application’s object design from the information model. That enables you to compose code that carries out CRUD operations without worrying about how the data is stored. Simply put, you work with the information using familiar.NET objects.In Entity Framework Core, the DbContext connects the domain classes to the database by serving as a bridge between them. You can make the most of the DbContext to query data in your entities or save your entities to the underlying database.I have actually talked about the essentials of DbContext in a previous post. In this postwe’ll dive into DbContext in a bit more information, discuss the DbContext life time, and provide some best practices for using DbContext in Entity Structure Core. EF Core allows you to instantiate a DbContext in numerous methods. We’ll take a look at a few of the options.To use the code examples offered in this short article, you need to have Visual Studio 2022 set up in your system. If you do not already have a copy, you can download Visual Studio 2022 here. Create an ASP.NET Core Web API task in Visual Studio 2022 To produce an ASP.NET Core 8 Web API job in Visual Studio 2022, follow the actions outlined listed below. Introduce the Visual Studio 2022 IDE. Click on”Create new task.” In the” Develop brand-new task” window, choose” ASP.NET Core Web API “from the list of design templates showed.

  1. Click Next. In the” Configure your new
  2. job “window, define the name and
  3. location for the brand-new project. Optionally inspect the”Location solution and job in the same directory site”check box, depending
  4. on your choices
  5. . Click Next. In the “Additional Details”window revealed next, choose”. WEB 8.0( Long Term Assistance)”as the structure version and ensure the”Usage controllers “box is unattended. We’ll be using minimal APIs in this project.
  6. Elsewhere in
  7. the “Additional Info” window, leave the”Authentication Type” set to” None”(the default )and guarantee the check boxes” Enable Open API Assistance,” “Configure for HTTPS,”and” Enable Docker”
  8. remain untreated. We will not be using any of those features here. Click Create. We’ll use this ASP.NET Core Web API job to deal with DbContext in the sections listed below. What is DbContext? Why is it needed?When dealing with Entity Framework Core, the DbContext represents a connection session with the database.
  9. It works as a system of work, making it possible for designers to keep an eye on and control changes made to entities before conserving them to the database.

We use the DbContext to recover information for our entities or persist our entities in the database.The DbContext class in EF Core abides by the System of Work and Repository patterns. It offers a way to encapsulate database reasoning within the application, making it easier to deal with the database and preserve code reusability and separation of issues. The DbContext in EF Core has

a number of responsibilities: Managing connections Querying information from the database Conserving data to the database Concurrency control Change tracking Caching Deal management The DbContext lifetime The DbContext class in Entity Structure Core plays an important role in assisting in the connection between the application and the database, supplying assistance for

  • data gain access to, modification tracking
  • , and transaction management. The life time
  • of a DbContext instance
  • begins when it is instantiated and ends when it is disposed.Here is the series of occasions in a common system of work using EF

    Core: A DbContext circumstances is developed. Entities are tracked utilizing this circumstances. Modifications are made to the tracked entities. The SaveChanges method is invoked to save the entities in memory to the underlying database. The DbContext object is disposed or garbage-collected when it is no longer required by the application. Avoid utilizing DbContext in using declarations A DbContext circumstances ought to be gotten rid of when it is no longer required to free up any unmanaged resources and

    1. avoid memory leaks.
    2. However, it is not a recommended practice to get rid of off DbContext circumstances explicitly or to utilize DbContext
    3. within an utilizing declaration. Here’s why you ought to not deal with your DbContext instances: When you dispose of
    4. a DbContext item, you may have one or more entities that can not be saved to the database.

    Instantiating and releasing DbContext things

    can be expensive, mainly when establishing a new database connection. Getting rid of the DbContext inside an using block after each use may lead to avoidable overhead and minimized efficiency. Disposing the DbContext item when database adjustments are pending or when you still expect to use the

    context might lead to issues or unexpected habits. Prematurely disposing of the DbContext circumstances may hinder change tracking, making more updates or questions hard or impossible.

  • Instead of utilizing blocks to get rid of the DbContext circumstances in your application, think about benefiting from dependency injection to manage their lifetime. Using dependence injection will guarantee that the DbContext is created and disposed of properly, depending upon the life cycle of the application or the scope of the operation.Create a new DbContext circumstances in EF Core There is no particular guideline for producing a DbContext circumstances. The requirements of your
  • application ought to figure out which approach you take. Each of the techniques illustrated listed below has its particular use cases– none of them is better than the others.You can extend the DbContext class in EF Core to develop your own DbContext class as revealed listed below. public class IDGDbContext: DbContext Similarly, you might instantiate a DbContextOptionsBuilder class and then utilize this instance to develop a circumstances of DbContextOptions. This DbContextOptions circumstances might then

    be passed to the DbContext fabricator. This method assists you explicitly create a DbContext instance.Use dependence injection to produce DbContext circumstances Alternatively, you can develop DbContext circumstances by means of dependency injection(DI)by configuring your DbContext instance utilizing the AddDbContext approach as revealed below.services.AddDbContext (choices => options.UseSqlServer(“name =ConnectionStrings: DefaultConnection”) ); You can then benefit from builder injection in your controller to obtain an instance of DbContext as shown below.public class IDGController Typically, an HTTP request-response cycle represents a system of work in web applications. With DI, we have the ability to produce a DbContext circumstances for each demand and deal with it when that request terminates.I prefer utilizing a DI container to instantiate and set up DbContext since the DI container manages the DbContext circumstances and lifetimes for you, relieving you of the pain of handling these instances explicitly.Initialize DbContext in the OnConfiguring approach A 3rd alternativeis to create a DbContext circumstances by bypassing the OnConfiguring approach in your custom DbContext class. You can then take advantage of the DbContext fabricator to pass setup information, such as a connection string.The code

    snippet listed below demonstrate how you can initialize DbContext in the OnConfiguring approach of your customized DbContext class.public class IDGDbContext: DbContext Register a factory to produce a DbContext instance You can also create an instance of DbContext using a factory. A factory comes in useful when your application needs to perform numerous systems of work within a specific scope.In this case, you can use the AddDbContextFactory approach to sign up a factory and develop your DbContext items as

    displayed in the code snippet offered below.services.AddDbContextFactory (alternatives=>

    options.UseSqlServer (“Specify your database connection string here.”) ); You can then utilize manufacturer injection in your controller to build DbContext instances as revealed below.private readonly IDbContextFactory _ dbContextFactory; public IDGController (IDbContextFactory dbContextFactory ) You can switch on delicate data logging to consist of application

    data when exceptions are logged in your application. The following code bit demonstrates how this can be done.optionsBuilder. EnableSensitiveDataLogging(). UseSqlServer (“Define your database connection string here.”); Finally, note that several parallel operations can not be performed all at once on the very same DbContext instance

    . This refers to both the parallel execution of async questions and any explicit use of numerous threads of the instance simultaneously. For that reason, it is recommended that parallel operations be performed utilizing separate instances of the DbContext. Additionally, you must never ever share DbContext circumstances between threads since it is not thread-safe. Copyright © 2024 IDG Communications, Inc. Source

  • Leave a Reply

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