Entity Framework Core is an object-relational mapper, or ORM, that isolates your software’s object mannequin from the information mannequin. That lets you write code that performs CRUD operations with out worrying about how the information is saved. In different phrases, you’re employed with the information 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 finest 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 offered on this article, it is best to have Visible Studio 2022 put in in your system. For those who don’t have already got a duplicate, you possibly can obtain Visible Studio 2022 right here.
Create an ASP.NET Core Internet API undertaking in Visible Studio 2022
To create an ASP.NET Core 8 Internet API undertaking in Visible Studio 2022, observe the steps outlined beneath.
- Launch the Visible Studio 2022 IDE.
- Click on on “Create new undertaking.”
- Within the “Create new undertaking” window, choose “ASP.NET Core Internet API” from the checklist of templates displayed.
- Click on Subsequent.
- Within the “Configure your new undertaking” window, specify the title and site for the brand new undertaking.
- Optionally examine the “Place resolution and undertaking in the identical listing” examine field, relying in your preferences.
- Click on Subsequent.
- Within the “Extra Data” window proven subsequent, choose “.NET 8.0 (Lengthy Time period Help)” because the framework model and ensure the “Use controllers” field is unchecked. We’ll be utilizing minimal APIs on this undertaking.
- Elsewhere within the “Extra Data” window, depart the “Authentication Kind” set to “None” (the default) and make sure the examine bins “Allow Open API Help,” “Configure for HTTPS,” and “Allow Docker” stay unchecked. We received’t be utilizing any of these options right here.
- Click on Create.
We’ll use this ASP.NET Core Internet API undertaking to work with DbContext within the sections beneath.
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 gives a technique to encapsulate database logic throughout the software, making it simpler to work with the database and keep code reusability and separation of considerations.
The DbContext in EF Core has a lot of tasks:
- 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 a vital position 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 technique is invoked to retailer the entities in reminiscence to the underlying database.
- The DbContext object is disposed or garbage-collected when it’s not wanted by the appliance.
Keep away from utilizing DbContext in utilizing statements
A DbContext occasion ought to be disposed when it’s not wanted to unencumber any unmanaged assets and stop reminiscence leaks. Nonetheless, it’s not a beneficial follow 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:
- If you eliminate a DbContext object, you could have a number of entities that can not be saved to the database.
- Instantiating and releasing DbContext objects may be costly, primarily when organising a brand new database connection.
- Eradicating the DbContext inside a utilizing block after every utilization might end in avoidable overhead and decreased efficiency.
- Disposing the DbContext object when database modifications are pending or while you nonetheless count on to make use of the context may result in issues or sudden habits.
- Prematurely disposing of the DbContext cases might intrude with change monitoring, making additional updates or queries troublesome or unimaginable.
As a substitute of utilizing utilizing
blocks to eliminate the DbContext cases in your software, take into account profiting from dependency injection to handle their lifetime. Utilizing dependency injection will be certain 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 isn’t a particular rule for making a DbContext occasion. The necessities of your software ought to decide which strategy you’re taking. Every of the approaches illustrated beneath has its particular use circumstances—none of them is best than the others.
You possibly can prolong the DbContext class in EF Core to create your individual DbContext class as proven beneath.
public class IDGDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> choices) : base(choices) { } }
Equally, you would 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 possibly can create DbContext cases through dependency injection (DI) by configuring your DbContext occasion utilizing the AddDbContext technique as proven beneath.
providers.AddDbContext<IDGDbContext>( choices => choices.UseSqlServer("title=ConnectionStrings:DefaultConnection"));
You possibly can then benefit from constructor injection in your controller to retrieve an occasion of DbContext as proven beneath.
public class IDGController { personal readonly IDGDbContext _dbContext; public IDGController(IDGDbContext dbContext) { _dbContext = dbContext; } }
Sometimes, an HTTP request-response cycle represents a unit of labor in net functions. With DI, we’re in a position to 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 technique
A 3rd possibility is to create a DbContext occasion by overriding the OnConfiguring technique in your customized DbContext class. You possibly can then benefit from the DbContext constructor to cross configuration data, resembling a connection string.
The code snippet beneath reveals how one can initialize DbContext within the OnConfiguring technique 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 facility to create a DbContext occasion
You can too create an occasion of DbContext utilizing a manufacturing facility. A manufacturing facility is useful when your software must carry out a number of items of labor inside a specific scope.
On this case, you should use the AddDbContextFactory technique to register a manufacturing facility and create your DbContext objects as proven within the code snippet given beneath.
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 beneath.
personal readonly IDbContextFactory<IDGDbContext> _dbContextFactory; public IDGController(IDbContextFactory<IDGDbContext> dbContextFactory) { _dbContextFactory = dbContextFactory; }
You possibly can activate delicate information logging to incorporate software information when exceptions are logged in your software. The next code snippet reveals how this may be carried out.
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. Subsequently, it’s endorsed 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’s not thread-safe.
Copyright © 2024 IDG Communications, Inc.