I’m encountering an issue with EF Core when trying to verify a database connection. The error message I’m receiving is:
Object cannot be cast from DBNull to other types
This is the relevant code throwing the error
public bool VerifyDatabaseConnection()
{
try
{
using (var db = new CarrierIpsContext())
{
Console.WriteLine("Attempting to open database connection...");
db.Database.OpenConnection();
Console.WriteLine("Database connection opened successfully.");
Console.WriteLine("Executing test query...");
db.Database.ExecuteSqlRaw("SELECT 1");
Console.WriteLine("Test query executed successfully.");
db.Database.CloseConnection();
Console.WriteLine("Database connection closed successfully.");
}
return true;
}
catch (Exception ex)
{
Console.WriteLine("Database connection failed");
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
return false;
}
}
In the console I can see the following
Attempting to open database connection...
Object cannot be cast from DBNull to other types.
It also states the problem is coming from this line
db.Database.OpenConnection();
I have verified that my database credentials are correct and from the same servers CLI I have successfully connected and performed operations on the remote database
Here is my context
internal class CarrierIpsContext: DbContext
{
public DbSet<CarrierIp> CarrierIps { get; set; }
private static readonly string connectionString = "Server=x.x.x.x; Database=somedb; Uid=someuser; Pwd=somepassword;";
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL(connectionString);
}
}
Relevant Info:
- Mariadb: V10.11.6
- Packages
- MySql.EntityFrameworkCore: V8.0.2
- Microsoft.EntityFrameworkCore: V8.0.6