Blazor Server with Entity Framework Core Code First

Sieber, Richard 5 Reputation points
2024-10-04T11:46:31.28+00:00

Hello,

we are currently evaluating the usability of Entity Framework Core Code First in a Blazor Server application.

We try to migrate from a Database First approach where we created a DbContext instance (by a IDbContextFactory) per database operation.

Example:

public class ReleaseService
{
   ...
   public Release LoadRelease(int userId, int releaseId)
   {
      using (var context = _contextFactory.CreateDbContext())
      {
         return context.Database.SqlQuery<Release>(
            @$"rel.SelRelease
               @person_id={userId},
               @release_id={releaseId}
            ")
            .AsEnumerable()
            .FirstOrDefault();
      }
   }
}

 

Our Blazor Server application currently uses cascading parameters where the MainLayout.razor cascades down certain class objects to child pages / components.

The most central entity is a User (entity). Therefore, we load it once in MainLayout.OnInitialized and cascade (pass) it down to child components.

 

Now, let’s consider following succession in our application:

  1. load User entity in MainLayout.OnInitialized
  2. navigate to any application page
  3. in an edit page load another entity, let’s say a Request entity
  4. edit some properties of the Request entity and save it; also set Request.UpdatedByUser during save

 

Question

Which approach would be better?

a)      long-living DbContext (lifetime: Scoped)

We create the DbContext in MainLayout.OnInitialized, do NOT close it here but cascade (pass) it down to every child component.

Once the user navigates to the edit page, we reuse the DbContext, manipulate Request entity and save the changes to database.

Consequence: The DbContext instance will live for the whole browser session of the current user.

b)     DbContext per operation

After loading the User entity in MainLayout.OnInitialized we directly close the DbContext.

Once the user navigates to the edit page, we create a new DbContext instance for our edit operation.

In this new DbContext instance we reload the User entity for having it in EF Core tracker.

We manipulate the Request entity by the edit page. On “Save” click we also set Request.UpdatedByUser and then save all changes to database.

Consequence: The secondly created DbContext instance will be closed only when the user navigates away from the edit page, more precisely: once the edit component with the “Save” functionality is destroyed.

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
754 questions
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,602 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 67,251 Reputation points
    2024-10-08T16:19:24.9033333+00:00

    code first vs database first has no impact on dbcontext usage. a dbcontext has one connection to the database. this generally means the dbcontext can only be used serially. if shared between threads (await), you must be sure there is no concurrent processing.

    in server Blazor, component event processing is asynchronous, and two components can trigger current asynchronous events. this means if there is a shared dbcontext, you must add locking to prevent concurrent access.so the best approach is a factory as in the samples.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.