When the connection string is in context (like the default state), it works correctly. But when I save the name of the connection string in the context (and connection string is in appsettings ), it encounters a data call error
You will have to use the DI function so that the instance of context class is automatically injected to the Razor Page.
(1) Delete (or comment out) the OnConfiguring method in the DbkabirContext class.
(2) Add the DbkabirContext to the DI container in the Program.cs, as follows:
namespace RazorPages1
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add following to enable DI
builder.Services.AddDbContext<DbkabirContext>(options =>
options.UseSqlServer(builder.Configuration
.GetConnectionString("DbkabirConnectionString")));
(3) Add private readonly DbkabirContext _context;
field to the cshtml.cs file and modify the constructor to have argument DbkabirContext context
, as follow:
public class IndexModel : PageModel
{
private readonly DbkabirContext _context;
public IndexModel(DbkabirContext context)
{
_context = context;
}
public void OnGet()
{
Users = _context.Users.Select( ...
...
}
}