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.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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:
public class BasePageModel : PageModel
public class BasePageModel : PageModel
{
protected DatabaseContext theDB = new();
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
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.
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();
}
}
}