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.

New contributor

TheDoc is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

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.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật