RazorPages - Efficiency of a database context in a PageModel

Geoff 0 Reputation points
2023-05-04T10:55:24.0933333+00:00

Hi all! I'm wondering how a database context object from SQL -> EF generation would work if I place it as a variable in a RazorPages PageModel. So:

  1. I have my own PageModel class which I inherit from the base RazorPages PageModel:
    public class BasePageModel : PageModel
  1. I add my DbContext (that is generated from SQL using the Scaffold tool) as a variable in the class:
    public class BasePageModel : PageModel
    {
        protected DatabaseContext theDB = new();
  1. Then every page in my website can use this DbContext.

Is this efficient? Will the same object be used in every page with persistence? Or is this the same as just adding the variable to every RazorPage? Or is it less efficient? Or is there a better way? Thanks for your help.

Regards Geoff

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,919 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,507 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,011 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 66,706 Reputation points
    2023-05-04T15:23:32+00:00

    a new Razor model instance is created on each request. so defining a variable in a base class is the same as defining it in every inheritor class.

    as suggested, it more common to inject a db context via services.

    0 comments No comments

  2. Karen Payne MVP 35,436 Reputation points
    2023-05-04T21:31:08.68+00:00

    Best to use a DbContext per page.

    Program.cs

    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
        builder.Services.AddRazorPages();
    
    
    builder.Services.AddDbContextPool<Context>(options =>
        options.UseSqlServer(
            Configurations.GetConfigurationRoot()
                .GetConnectionString("DefaultConnection")));
    
    var app = builder.Build();
    

    Example usage for a page

    public class CustomersModel : PageModel
    {
        private readonly Context _context;
        private readonly ILogger<IndexModel> _logger;
        public CustomersModel(ILogger<IndexModel> logger, Data.Context context)
        {
            _context = context;
            _logger = logger;
        }
    
        public IList<Customers> Customers { get;set; } = default!;
    
        public async Task OnGetAsync()
        {
            if (_context.Customers != null)
            {
                Customers = await _context.Customers
                    .Include(c => c.Contact)
                    .Include(c => c.ContactTypeIdentifierNavigation)
                    .Include(c => c.CountryIdentifierNavigation).ToListAsync();
            }
        }
    }
    
    0 comments No comments

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.