0

I have a .Net 5 application and want to add Ef Core with Postgres support. I want to validate the database connection string coming from IConfiguration. Based on this question

How to check is connection string valid?

I know that builders inheriting from SqlConnectionStringBuilder check the connection string in the constructor. So I created a demo code how the validation could look like

bool Validate(IConfiguration options)
{
    try
    {
        string databaseConnectionString = options.GetConnectionString("Database");
        _ = new NpgsqlConnectionStringBuilder(databaseConnectionString);

        return true;
    }
    catch (Exception exception)
    {
        return false;
    }
}

I had a look at the NpgsqlConnectionStringBuilder

https://www.npgsql.org/doc/api/Npgsql.NpgsqlConnectionStringBuilder.html

and see that it does not inherit from the SqlConnectionStringBuilder. It does not provide a method to validate a connection string.

Does someone know if that class performs a connection string validation when constructing the instance?

Question3r
  • 2,166
  • 19
  • 100
  • 200

1 Answers1

2

SqlConnectionStringBuilder is the SqlClient connection string builder, so specific to Microsoft's SQL Server database. Both SqlConnectionStringBuilder and NpgsqlConnectionStringBuilder derive from DbConnectionStringBuilder, which is the database-agnostic base class.

And yes, NpgsqlConnectionStringBuilder validates the string - you can give it a try with a bad connection string. However, this doesn't guarantee that connecting will actually succeed - just the that connection-string is well-formed and doesn't try to use unsupported options, etc. Consider just trying to open a connection instead.

Shay Rojansky
  • 15,357
  • 2
  • 40
  • 69
  • Why does `NpgsqlConnectionStringBuilder` allow you to pass an empty or null `connectionString` to the ctor and not validate it? – sp7 Oct 04 '21 at 20:28
  • You can pass an empty string, but you'll get an exception when you attempt to open the connection. This is similar to instantiating an NpgsqlConnection without passing any connection string - it's just the initial state of the object. – Shay Rojansky Oct 05 '21 at 09:52