Search code examples
c#asp.net-coreblazor-webapp

Is this Blazor/EF Core code efficient and safe use of DbContext and accessing shadow properties


Simple Blazor Web App created in VS2022 using the wb app template , to edit a vendor record. All works and I can edit the record in concurrent browser tabs.

I've seen examples on SO of how to use DbContext DI but these do not offer Intellisense access to the shadow properties in my app DbContext class.

So, I have used an approach (see code) where i inject my application's db context.

Specifically, I was wondering whether injection of my LicensingContext class , to obtain Intellisense access to the shadow properties of the DbSets , is going to cause achy issues or inefficient? and why.

The context appears to be created and disposed suitably.

LicensingContext (my App DbContext class)

// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

namespace Licensing.Models;


public partial class LicensingContext : Microsoft.EntityFrameworkCore.DbContext
{


    DateTime dt = DateTime.Now;

    public LicensingContext(DbContextOptions<LicensingContext> options)
        : base(options)
    {
        Console.WriteLine(string.Format("+++ Licensing context CREATED {0}", dt));
    }
    
    ~LicensingContext()
    {
        Console.WriteLine(string.Format("--- Licensing context DESTROYED {0}", dt));
    }


    public virtual DbSet<Allocations> Allocations { get; set; }

    public virtual DbSet<Dates> Dates { get; set; }

    public virtual DbSet<Departments> Departments { get; set; }

    public virtual DbSet<VendorBundles> VendorBundles { get; set; }

    public virtual DbSet<VendorLicenceModules> VendorLicenceModules { get; set; }

    public virtual DbSet<Vendors> Vendors { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Allocations>(entity =>
        {
            entity.HasKey(e => e.pkId).HasName("PK_fctAllocation_1");

            entity.HasOne(d => d.Department).WithMany(p => p.Allocations).HasConstraintName("FK_fctAllocation_dimDepartment");

            entity.HasOne(d => d.VendorBundle).WithMany(p => p.Allocations)
                .OnDelete(DeleteBehavior.ClientSetNull)
                .HasConstraintName("FK_fctAllocation_dimVendorBundle");

            entity.HasOne(d => d.Vendor).WithMany(p => p.Allocations).HasConstraintName("FK_fctAllocation_dimVendor");

            entity.HasOne(d => d.VendorLicenceModule).WithMany(p => p.Allocations)
                .OnDelete(DeleteBehavior.ClientSetNull)
                .HasConstraintName("FK_fctAllocation_dimVendorLicenceModule");
        });

        modelBuilder.Entity<Dates>(entity =>
        {
            entity.HasKey(e => e.pkId).HasName("PK_dimDates");

            entity.Property(e => e.MMYYYY).IsFixedLength();
            entity.Property(e => e.Style101).IsFixedLength();
            entity.Property(e => e.Style103).IsFixedLength();
            entity.Property(e => e.Style112).IsFixedLength();
            entity.Property(e => e.Style120).IsFixedLength();
            entity.Property(e => e.TheDaySuffix).IsFixedLength();
        });

        modelBuilder.Entity<Departments>(entity =>
        {
            entity.HasKey(e => e.pkId).HasName("PK_dimDepartment");

            entity.Property(e => e.Notes).IsFixedLength();
        });

        modelBuilder.Entity<VendorBundles>(entity =>
        {
            entity.HasKey(e => e.pkId).HasName("PK_dimVendorBundle");

            entity.HasOne(d => d.VendorFkNavigation).WithMany(p => p.VendorBundles).HasConstraintName("FK_dimVendorBundle_dimVendor");
        });

        modelBuilder.Entity<VendorLicenceModules>(entity =>
        {
            entity.HasKey(e => e.pkId).HasName("PK_dimLicenceModules");

            entity.HasOne(d => d.Bundle).WithMany(p => p.VendorLicenceModules).HasConstraintName("FK_dimVendorLicenceModule_dimVendorBundle");
        });

        modelBuilder.Entity<Vendors>(entity =>
        {
            entity.HasKey(e => e.pkId).HasName("PK_dimVendor_1");
        });

        OnModelCreatingPartial(modelBuilder);
    }

    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}

VendorDetails (parent class)

@* @page "/Vendors/createedit" *@

@* using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.JSInterop;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Web; *@
@* using Microsoft.AspNetCore.Identity; *@
@using Microsoft.EntityFrameworkCore
@using Licensing.Models

@* @using Microsoft.AspNetCore.Identity; *@
@* @using Microsoft.AspNetCore.Authorization *@
@* @attribute [Authorize] *@


@* @inject IDbContextFactory<Licensing.Models.LicensingContext> DbFactory *@

@inject NavigationManager NavigationManager

<RadzenContent Container="main">
    <ChildContent>
        <div class="row">
            <div class="col-md-12">
                <RadzenTemplateForm Data="@Vendor" Visible="@(Vendor != null)" TItem="Licensing.Models.Vendors" Submit="@FormSubmit">
                    <ChildContent>

                        <div style="margin-bottom: 1rem" class="row">
                            <div class="col-md-3">
                                <RadzenLabel Text="Name" Component="Name" style="width: 100%" />
                            </div>
                            <div class="col-md-9">
                                <RadzenTextBox MaxLength="256" style="display:block; width: 100%" @bind-Value="@(Vendor.Name)" Name="Name" />
                                <RadzenRequiredValidator Component="Name" Text="Name is required" style="position: absolute" />
                            </div>
                        </div>

                        <div style="margin-bottom: 1rem" class="row">
                            <div class="col-md-3">
                                <RadzenLabel Text="Email" Component="Email" style="width: 100%" />
                            </div>
                            <div class="col-md-9">
                                <RadzenTextBox MaxLength="256" style="display: block; width: 100%" @bind-Value="@(Vendor.Email)" Name="Email" />
                                <RadzenRequiredValidator Component="Email" Text="Email is required" style="position: absolute" />
                            </div>
                        </div>

                        <div style="margin-bottom: 1rem" class="row">
                            <div class="col-md-3">
                                <RadzenLabel Text="Last Name" Component="LastName" style="width: 100%">
                                </RadzenLabel>
                            </div>
                            <div class="col-md-9">
                                <RadzenTextBox>
                                    @* MaxLength="256" style="width: 100%" @bind-Value="@(Vendor.LastName)" Name="LastName"> *@
                                </RadzenTextBox>
                            </div>
                        </div>

                        <div style="margin-bottom: 1rem" class="row">
                            <div class="col-md-3">
                                <RadzenLabel Text="First Name" Component="FirstName" style="width: 100%">
                                </RadzenLabel>
                            </div>
                            <div class="col-md-9">
                                <RadzenTextBox>
                                    @* MaxLength="256" style="width: 100%" @bind-Value="@(Vendor.FirstName)" Name="FirstName"> *@
                                </RadzenTextBox>
                            </div>
                        </div>

                        <div style="margin-bottom: 1rem" class="row">
                            <div class="col-md-3">
                                <RadzenLabel Text="Phone" Component="Phone" style="width: 100%">
                                </RadzenLabel>
                            </div>
                            <div class="col-md-9">
                                <RadzenTextBox>
                                    @* MaxLength="256" style="width: 100%" @bind-Value="@(Vendor.Phone)" Name="Phone"> *@
                                </RadzenTextBox>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col offset-sm-3">
                                <RadzenButton ButtonType="ButtonType.Submit" Icon="save" Text="Save" ButtonStyle="ButtonStyle.Primary">
                                </RadzenButton>
                                <RadzenButton ButtonStyle="ButtonStyle.Light" style="margin-left: 1rem" Text="Cancel" Click="@ButtonCancelClick">
                                </RadzenButton>
                            </div>
                        </div>
                    </ChildContent>
                </RadzenTemplateForm>
            </div>
        </div>
    </ChildContent>
</RadzenContent>

@code {
    [Parameter(CaptureUnmatchedValues = true)]
    public IReadOnlyDictionary<string, dynamic>? Attributes { get; set; }

    [Inject]
    protected NotificationService NotificationService { get; set; } = default!;

    [Inject]
    protected DialogService DialogService { get; set; } = default!;


    protected Licensing.Models.Vendors? Vendor { get; set; }
      

    protected virtual async System.Threading.Tasks.Task FormSubmit(Licensing.Models.Vendors args) { }


    protected async System.Threading.Tasks.Task ButtonCancelClick(MouseEventArgs args)
    {
        await Task.Run(() => DialogService.Close(null));
    }

}

EditVendor.razor (subclass)

@*
    DCE Aug 24

    This is a dervied class from CreateEdit component class.
    CreateEdit is reused such that entities can be created or edited.
    Each subclass will perform any validation needed.

    be sure to use base.BuildRenderTree as this is only called for the parent class.
*@

@page "/vendors/edit"
@using Microsoft.EntityFrameworkCore

@inherits VendorDetails

<PageTitle>Edit</PageTitle>

@{
    base.BuildRenderTree(__builder);
}

@code {

    [Parameter] public int Id { get; set; }

    [Inject]
    public LicensingContext? Context { get; set; }


    protected override async System.Threading.Tasks.Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        base.Vendor = Context!.Vendors.FirstOrDefault(x => x.pkId == Id);
    }


    protected override async System.Threading.Tasks.Task FormSubmit(Licensing.Models.Vendors args)
    {
        if (base.Vendor != null)
        {
            try
            {
                await InvokeAsync(() => Context!.SaveChangesAsync());
                DialogService.Close();

            }
            catch (System.Exception e)
            {
                NotificationService.Notify(
                    new NotificationMessage()
                        {
                            Severity = NotificationSeverity.Error,
                            Summary = $"Error: Unable to save Vendor!",
                            Detail = string.Format("Msg:{0}", e.Message.ToString())
                        });
            }
        }
    }
}

Tried to use the @inject IDBFactory ... in the razor component but this did not give me access to shadow properties , therefore I created a class field Context that holds an instance of my Apps DbContext class, LicensingContext

EDIT 1 LicensingContext is registered as a service (for dbContext) in the Program.cs file.


Solution

  • I was wondering whether injection of my LicensingContext class, to obtain Intellisense access to the shadow properties of the DbSets , is going to cause achy issues or inefficient? and why.

    Typically, this does not cause serious problems or inefficiencies. However, if the LicensingContext is injected via Dependency Injection (DI) and frequently operated on, it could lead to performance issues. Therefore, it is important to ensure that the scope of the context object is correctly configured in the lifecycle management.

    Configuring DbContext as scoped is the recommended approach to balance performance and resource usage:

    LicensingContext is registered as a service (for dbContext) in the Program.cs file.

    Cause you registered the DbContext, using the code like builder.Services.AddDbContext<YourDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

    By default, the AddDbContext method configures DbContext as scoped. This means that a new DbContext instance is created for each request or operation, but within the same request, the DbContext instance is shared.

    this did not give me access to shadow properties

    By the way, it seems that you haven't configured the shadow properties of the entity in your OnModelCreating method.

    You can configure shadow properties using Property<TProperty>(String).

    // for example:
    modelBuilder.Entity<Blog>()
                .Property<DateTime>("LastUpdated");
    

    You can access shadow properties through the ChangeTracker API:

    // for example:
    context.Entry(myBlog).Property("LastUpdated").CurrentValue = DateTime.Now;
    

    You can refer to this official documentation for guidance.