Hi @Butachan
You can try to use Dependency injection and create a Singleton service.
Like this: since I didn't install the oracle package, I just use the sql server package to test. You can change it to yours.
//using Microsoft.Data.SqlClient;
public interface IDataRepository
{
SqlConnection connection { get; set; }
SqlConnection transaction { get; set; }
string GetConnection();
}
public class DataRepository : IDataRepository
{
public SqlConnection connection { get; set; }
public SqlConnection transaction { get; set; }
public string GetConnection()
{
return connection.ConnectionString + "******** status: " + connection.State;
}
}
Then, register the services as Singleton in the program.cs file:
builder.Services.AddSingleton<IDataRepository, DataRepository>();
After that, inject the service in the razor page .cshtml file:
public class CreateEmployeeModel : PageModel
{
private readonly IDataRepository _datarepo;
private readonly IConfiguration _config;
public CreateEmployeeModel(IDataRepository dataRepository, IConfiguration config)
{
_datarepo = dataRepository;
_config=config;
}
[BindProperty]
public Employee NewEmployee { get; set; }
public void OnGet()
{
SqlConnection connection = new SqlConnection(_config.GetConnectionString("DefaultConnection2"));
connection.Open();
_datarepo.connection = connection;
var state = _datarepo.GetConnection();
}
public IActionResult OnPostAsync()
{
var state = _datarepo.GetConnection();
#region
var newemp = NewEmployee;
var showerror = true; //assume there has an error and we want to show the error.
if (showerror)
{
ViewData["showerror"]="true"; //used to set the display attribute.
ViewData["customerror"]="the custom error message"; //show the custom error message.
return Page();
}
#endregion
return RedirectToPage("./Index");
}
}
The result as below: after submitting the form, the connection status is Open
in the Post method.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion