Entity Framework Core is an object-relational mapper, or ORM, that isolates your utility’s object mannequin from the info mannequin. That lets you write code that performs CRUD operations with out worrying about how the info is saved. In different phrases, you’re employed with the info utilizing acquainted .NET objects.
In Entity Framework Core, the DbContext connects the area lessons to the database by performing as a bridge between them. You possibly can benefit from the DbContext to question information in your entities or save your entities to the underlying database.
I’ve mentioned the fundamentals of DbContext in a earlier article. On this article we’ll dive into DbContext in a bit extra element, focus on the DbContext lifetime, and provide some greatest practices for utilizing DbContext in Entity Framework Core. EF Core lets you instantiate a DbContext in a number of methods. We’ll look at a few of the choices.
To make use of the code examples supplied on this article, it is best to have Visible Studio 2022 put in in your system. When you don’t have already got a duplicate, you’ll be able to obtain Visible Studio 2022 right here.
Create an ASP.NET Core Net API challenge in Visible Studio 2022
To create an ASP.NET Core 8 Net API challenge in Visible Studio 2022, comply with the steps outlined under.
- Launch the Visible Studio 2022 IDE.
- Click on on “Create new challenge.”
- Within the “Create new challenge” window, choose “ASP.NET Core Net API” from the listing of templates displayed.
- Click on Subsequent.
- Within the “Configure your new challenge” window, specify the identify and site for the brand new challenge.
- Optionally examine the “Place answer and challenge in the identical listing” examine field, relying in your preferences.
- Click on Subsequent.
- Within the “Further Info” window proven subsequent, choose “.NET 8.0 (Lengthy Time period Assist)” because the framework model and ensure the “Use controllers” field is unchecked. We’ll be utilizing minimal APIs on this challenge.
- Elsewhere within the “Further Info” window, go away the “Authentication Sort” set to “None” (the default) and make sure the examine packing containers “Allow Open API Assist,” “Configure for HTTPS,” and “Allow Docker” stay unchecked. We gained’t be utilizing any of these options right here.
- Click on Create.
We’ll use this ASP.NET Core Net API challenge to work with DbContext within the sections under.
What’s DbContext? Why is it wanted?
When working with Entity Framework Core, the DbContext represents a connection session with the database. It really works as a unit of labor, enabling builders to observe and management modifications made to entities earlier than saving them to the database. We use the DbContext to retrieve information for our entities or persist our entities within the database.
The DbContext class in EF Core adheres to the Unit of Work and Repository patterns. It supplies a approach to encapsulate database logic throughout the utility, making it simpler to work with the database and preserve code reusability and separation of considerations.
The DbContext in EF Core has a variety of obligations:
- Managing connections
- Querying information from the database
- Saving information to the database
- Concurrency management
- Change monitoring
- Caching
- Transaction administration
The DbContext lifetime
The DbContext class in Entity Framework Core performs an important function in facilitating the connection between the appliance and the database, offering assist for information entry, change monitoring, and transaction administration. The lifetime of a DbContext occasion begins when it’s instantiated and ends when it’s disposed.
Right here is the sequence of occasions in a typical unit of labor utilizing EF Core:
- A DbContext occasion is created.
- Entities are tracked utilizing this occasion.
- Modifications are made to the tracked entities.
- The SaveChanges methodology is invoked to retailer the entities in reminiscence to the underlying database.
- The DbContext object is disposed or garbage-collected when it’s now not wanted by the appliance.
Keep away from utilizing DbContext in utilizing statements
A DbContext occasion ought to be disposed when it’s now not wanted to unencumber any unmanaged sources and stop reminiscence leaks. Nevertheless, it isn’t a advisable observe to dispose off DbContext cases explicitly or to make use of DbContext inside a utilizing
assertion.
Right here’s why you shouldn’t eliminate your DbContext cases:
- While you eliminate a DbContext object, you could have a number of entities that can’t be saved to the database.
- Instantiating and releasing DbContext objects will be costly, primarily when establishing a brand new database connection.
- Eradicating the DbContext inside a utilizing block after every utilization could lead to avoidable overhead and diminished efficiency.
- Disposing the DbContext object when database modifications are pending or if you nonetheless count on to make use of the context would possibly result in issues or sudden habits.
- Prematurely disposing of the DbContext cases could intervene with change monitoring, making additional updates or queries troublesome or unimaginable.
As an alternative of utilizing utilizing
blocks to eliminate the DbContext cases in your utility, contemplate profiting from dependency injection to handle their lifetime. Utilizing dependency injection will be sure that the DbContext is created and disposed of appropriately, relying on the life cycle of the appliance or the scope of the operation.
Create a brand new DbContext occasion in EF Core
There is no such thing as a particular rule for making a DbContext occasion. The necessities of your utility ought to decide which strategy you’re taking. Every of the approaches illustrated under has its particular use circumstances—none of them is best than the others.
You possibly can lengthen the DbContext class in EF Core to create your personal DbContext class as proven under.
public class IDGDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> choices) : base(choices) { } }
Equally, you may instantiate a DbContextOptionsBuilder class after which use this occasion to create an occasion of DbContextOptions. This DbContextOptions occasion might then be handed to the DbContext constructor. This strategy helps you explicitly create a DbContext occasion.
Use dependency injection to create DbContext cases
Alternatively, you’ll be able to create DbContext cases through dependency injection (DI) by configuring your DbContext occasion utilizing the AddDbContext methodology as proven under.
providers.AddDbContext<IDGDbContext>( choices => choices.UseSqlServer("identify=ConnectionStrings:DefaultConnection"));
You possibly can then benefit from constructor injection in your controller to retrieve an occasion of DbContext as proven under.
public class IDGController { personal readonly IDGDbContext _dbContext; public IDGController(IDGDbContext dbContext) { _dbContext = dbContext; } }
Usually, an HTTP request-response cycle represents a unit of labor in net functions. With DI, we’re capable of create a DbContext occasion for every request and eliminate it when that request terminates.
I want utilizing a DI container to instantiate and configure DbContext as a result of the DI container manages the DbContext cases and lifetimes for you, relieving you of the ache of managing these cases explicitly.
Initialize DbContext within the OnConfiguring methodology
A 3rd possibility is to create a DbContext occasion by overriding the OnConfiguring methodology in your customized DbContext class. You possibly can then benefit from the DbContext constructor to go configuration info, equivalent to a connection string.
The code snippet under exhibits how one can initialize DbContext within the OnConfiguring methodology of your customized DbContext class.
public class IDGDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Specify your database connection string right here."); } }
Register a manufacturing unit to create a DbContext occasion
It’s also possible to create an occasion of DbContext utilizing a manufacturing unit. A manufacturing unit is useful when your utility must carry out a number of models of labor inside a selected scope.
On this case, you need to use the AddDbContextFactory methodology to register a manufacturing unit and create your DbContext objects as proven within the code snippet given under.
providers.AddDbContextFactory<IDGDbContext>( choices => choices.UseSqlServer("Specify your database connection string right here."));
You possibly can then use constructor injection in your controller to assemble DbContext cases as proven under.
personal readonly IDbContextFactory<IDGDbContext> _dbContextFactory; public IDGController(IDbContextFactory<IDGDbContext> dbContextFactory) { _dbContextFactory = dbContextFactory; }
You possibly can activate delicate information logging to incorporate utility information when exceptions are logged in your utility. The next code snippet exhibits how this may be achieved.
optionsBuilder .EnableSensitiveDataLogging() .UseSqlServer("Specify your database connection string right here.");
Lastly, word that a number of parallel operations can’t be executed concurrently on the identical DbContext occasion. This refers to each the parallel execution of async queries and any specific use of a number of threads of the occasion concurrently. Due to this fact, it is suggested that parallel operations be carried out utilizing separate cases of the DbContext. Moreover, it is best to by no means share DbContext cases between threads as a result of it isn’t thread-safe.
Copyright © 2024 IDG Communications, Inc.