GetSchema(“Databases”) on ODBC connection (C#)

梦想的初衷 提交于 2019-12-11 14:22:10

问题


I am testing various DB connection methods in C#. In particular, I am testing SqlConnection and OdbcConnection classes; my DB is SQLServer Express (.\SQLEXPRESS). Both are working reasonably well, except in listing available databases on the server.

In my test code I use a "generic" DbConnection object and a simple factory to create an instance of specific SqlConnetion and OdbcConnetion subclasses (they both derive from DbConnection):

DbConnection connection;
switch (connection_type)
{
case DbConnectionType.DBCONN_MSSQL:
   connection = new SqlConnection(...sql connection string...);
   break;
case DbConnectionType.DBCONN_ODBC:
  connection = new OdbcConnection(...odbc connection string...);
  break;
}

The trick seems to work well except when I try to get the list of databases on the server:

DataTable databases = connection.GetSchema("Databases");
foreach (DataRow database in databases.Rows)
{
   String databaseName = database["database_name"] as String;
   Console.WriteLine(databaseName);
}

When "connection" is an OdbcConnection (and, note, the database is the same), I get an exception saying that "Databases" key was not found. I listed all the keys exposed by GetSchema(), and the ODBC version returns only a subset of the items exposed by the SQLServer version. I couldn't find any hint about this specific problem. Is it a documented/expected behaviour? Am I doing something wrong?

NOTE: here how I build the ODBC connection string:

   OdbcConnectionStringBuilder builder;

   builder = new OdbcConnectionStringBuilder();
   builder.Driver = "SQL Server";
   builder.Add("Server", ".\\SQLEXPRESS");
   builder.Add("Uid", "");
   builder.Add("Pwd", ""); // Using current user
   builder.Add("Integrated Security", "SSPI");

   connection = new OdbcConnection(builder.ConnectionString);

回答1:


Is it a documented/expected behaviour?

Yes. See Retrieving Database Schema Information

Am I doing something wrong?

If your goal is to read SQL Server metadata in a provider-agnostic way, then yes. You should query the SQL Server catalog views directly. sys.databases, sys.tables, etc.




回答2:


Make sure your "Databases" model has a valid Key. Add the [Key] Data annotation if the key you want to implement for that database doesn't follow the "ClassName"+"ID" entity framework rule.



来源:https://stackoverflow.com/questions/50179983/getschemadatabases-on-odbc-connection-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!