Defining primary key columns via GetSchema

Is there a way to determine if a column is a primary key using the ADO.NET method GetSchema?

Here is what I have so far:

public IEnumerable<DbColumnInfo> GetColumns(string providerName, string connectionString, string tableName)
{
    DbProviderFactory factory = DbProviderFactories.GetFactory(providerName);
    using (DbConnection connection = factory.CreateConnection())
    using (DbCommand command = factory.CreateCommand())
    {
        connection.ConnectionString = connectionString;
        connection.Open();
        command.Connection = connection;

        var columns = connection.GetSchema("Columns", tableName.Split('.'));
        foreach (DataRow row in columns.Rows)
        {
            yield return new DbColumnInfo()
            {
                Name = row.Field<string>(3),
                OrdinalPosition = row.Field<short>(4),
                DataType = this.FormatDataType(row),
                IsNullable = string.Equals(row.Field<string>(6), "yes", StringComparison.InvariantCultureIgnoreCase),
                IsPrimaryKey = // ... ?
            };
        }
    }
}
+5
source share
6 answers

I am afraid that you cannot define with connection.GetSchema () ...

But as a workaround, you can try the dataadapter if it suits you:

    var da = factory.CreateDataAdapter();
    command.CommandText = "select * from Employees";
    da.SelectCommand = command;
    da.MissingSchemaAction = MissingSchemaAction.AddWithKey;

    var dtab = new DataTable();
    da.FillSchema(dtab, SchemaType.Source);

    foreach (DataColumn col in dtab.Columns)
    {
        string name = col.ColumnName;
        bool isNull = col.AllowDBNull;
        bool isPrimary = dtab.PrimaryKey.Contains(col);
    }
+4
source

qes , ( , , ) , , . DbInfoProvider, DbTableInfo DbColumnInfo . SqlDbInfoProvider SQL Server:

public IEnumerable<DbColumnInfo> GetColumns(string connectionString, DbTableInfo table)
{
    DbProviderFactory factory = DbProviderFactories.GetFactory(this.providerName);
    using (DbConnection connection = factory.CreateConnection())
    using (DbCommand command = factory.CreateCommand())
    {
        connection.ConnectionString = connectionString;
        connection.Open();
        command.Connection = connection;
        command.CommandText = ColumnInfoQuery;
        command.CommandType = CommandType.Text;
        var tableSchema = factory.CreateParameter();
        tableSchema.ParameterName = "@tableSchema";
        tableSchema.DbType = DbType.String;
        tableSchema.Value = table.Schema;
        command.Parameters.Add(tableSchema);
        var tableName = factory.CreateParameter();
        tableName.ParameterName = "@tableName";
        tableName.DbType = DbType.String;
        tableName.Value = table.Name;
        command.Parameters.Add(tableName);

        var dataTable = new DataTable();
        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                yield return new DbColumnInfo()
                {
                    Name = reader.GetString(0),
                    OrdinalPosition = reader.GetInt32(1),
                    DataType = reader.GetString(2),
                    IsNullable = reader.GetBoolean(3),
                    IsPrimaryKey = reader.GetBoolean(4),
                    IsForeignKey = reader.GetBoolean(5),
                    IsUnique = reader.GetBoolean(6),
                };
            }
        }
    }
}

ColumnInfoQuery - , :

SELECT c.[column_name]
     , CAST(c.[ordinal_position] AS int) [ordinal_position]
     , CASE WHEN c.[data_type] IN ( 'bit', 'date', 'datetime', 'smalldatetime', 'int', 'bigint', 'smallint', 'tinyint', 'real', 'money', 'smallmoney', 'image', 'text', 'ntext' )  THEN c.[data_type]
            WHEN c.[character_maximum_length] IS NOT NULL
            THEN c.[data_type] + '(' + CAST(c.[character_maximum_length] AS VARCHAR(30)) + ')'
            WHEN c.[datetime_precision] IS NOT NULL 
            THEN c.[data_type] + '(' + CAST(c.[datetime_precision] AS VARCHAR(30)) + ')'
            WHEN c.[numeric_scale] IS NOT NULL 
            THEN c.[data_type] + '(' + CAST(c.[numeric_precision] AS VARCHAR(30)) + ',' + CAST(c.[numeric_scale] AS VARCHAR(30)) + ')'
            WHEN c.[numeric_precision] IS NOT NULL 
            THEN c.[data_type] + '(' + CAST(c.[numeric_precision] AS VARCHAR(30)) + ')'
            ELSE c.[data_type]
       END [data_type]
     , CAST(MAX(CASE c.[is_nullable] WHEN 'YES' THEN 1 ELSE 0 END) AS bit) [is_nullable]
     , CAST(MAX(CASE WHEN pk.[constraint_type] = 'PRIMARY KEY' THEN 1 ELSE 0 END) AS bit) [is_primary_key]
     , CAST(MAX(CASE WHEN pk.[constraint_type] = 'FOREIGN KEY' THEN 1 ELSE 0 END) AS bit) [is_foreign_key]
     , CAST(MAX(CASE WHEN pk.[constraint_type] = 'FOREIGN KEY' THEN 0 ELSE 1 END) AS bit) [is_unique]
FROM information_schema.columns c
LEFT JOIN information_schema.constraint_column_usage ccu 
        ON c.[column_name] = ccu.[column_name] 
        AND c.[table_name] = ccu.[table_name] 
        AND c.[table_schema] = ccu.[table_schema]
        AND c.[table_catalog] = ccu.[table_catalog]
LEFT JOIN information_schema.table_constraints pk 
        ON pk.[constraint_name] = ccu.[constraint_name]
        AND pk.[table_name] = ccu.[table_name] 
        AND pk.[constraint_schema] = ccu.[table_schema]
        AND pk.[constraint_catalog] = ccu.[table_catalog]
        AND pk.[constraint_type] IN ( 'PRIMARY KEY', 'FOREIGN KEY', 'UNIQUE' )
WHERE c.[table_schema] = @tableSchema
        AND c.[table_name] = @tableName
GROUP BY c.[table_schema], c.[table_name], c.[column_name], c.[ordinal_position]
       , c.[data_type], c.[character_maximum_length], c.[datetime_precision]
       , c.[numeric_precision], c.[numeric_scale], c.[is_nullable]
+3

, , , . /

DataTable indexes = conn.GetSchema("Indexes");
List<string> PrimaryKeys = new List<string>();
foreach (DataRow row in indexes.Rows)
  if (Convert.ToBoolean(row["PRIMARY_KEY"]))
    PrimaryKeys.Add(row["TABLE_NAME"] + "." + row["COLUMN_NAME"]);

PrimaryKeys . , [table]. [column] .

+2

SQLITE , , : -

            string[] restrictions = new string[] { null, null,   strTable };
            DataTable tableInfo = Connection.GetSchema("IndexColumns", restrictions);

            if (tableInfo == null)
                throw new Exception("TableInfo null Error");

            foreach (DataRow test in tableInfo.Rows)
            {
                Console.WriteLine(test["column_name"]);             
            }
0

ODP.Net Oracle "PrimaryKeys" GetSchema(). GetSchema() , , . GetSchema(), GetSchema() Oracle.

    private void GetSchemaMetaInfo(DbConnection connection)
    {
        var metaDataCollections = connection.GetSchema("MetaDataCollections");
        var dataSourceInformation = connection.GetSchema("DataSourceInformation");
        var dataTypes = connection.GetSchema("DataTypes");
        var restrictions = connection.GetSchema("Restrictions");
        var reservedWords = connection.GetSchema("ReservedWords");
    }
0

PrimaryKeys , , , IndexColumns.

String pkIndxNm = null;
List<String> lstPkColNms = new List<String>();

DataTable dt = dbConn.GetSchema("PrimaryKeys", new[] { owner, tblNm });
if (dt.Rows.Count == 1) {
    DataRow pkRow = dt.Rows[0];
    pkIndxNm = pkRow["INDEX_NAME"] as String;

    // Now use the IndexColumns collection to pick up the names of the 
    // columns which constitute the primary key.
    //
    dt = dbConn.GetSchema("IndexColumns", new[] { owner, pkIndxNm });
    foreach (DataRow icRow in dt.Rows) {
        String colNm = icRow["COLUMN_NAME"] as String;
        lstPkColNms.Add(colNm);
    }
}

Oracle, System.Data.Common.DbConnection System.Data.OracleClient.

. GetSchema . , DataTable - , :

  DataTable dt = dbConn.GetSchema("Restrictions");
  AppLog.Log.Info("CollectionName | RestrictionName | ParameterName | " +
                  "RestrictionDefault | RestrictionNumber");
  AppLog.Log.Info(" ");
  foreach (DataRow r in dt.Rows) {
      String s = r["CollectionName"] as String;
      s += " | " + r["RestrictionName"] as String;
      s += " | " + r["ParameterName"] as String;
      s += " | " + r["RestrictionDefault"] as String;
      s += " | " + r["RestrictionNumber"].ToString();
      AppLog.Log.Info(s);
  }

, indexName 1 2 , .

| UserName | | USERNAME | 1

| | | | 1

| | TABLENAME | TABLE_NAME | 2

| | | | 1

| | TABLENAME | TABLE_NAME | 2

| | COLUMNNAME | COLUMN_NAME | 3

| | | | 1

| | VIEWNAME | VIEW_NAME | 2

| | | | 1

| | SYNONYMNAME | SYNONYM_NAME | 2

| | | SEQUENCE_OWNER | 1

| | | SEQUENCE_NAME | 2

| | | | 1

| ObjectName | OBJECTNAME | OBJECT_NAME | 2

| | | | 1

| | | OBJECT_NAME | 2

IndexColumns | | | INDEX_OWNER | 1

IndexColumns | | | INDEX_NAME | 2

IndexColumns | TableOwner | TABLEOWNER | TABLE_OWNER | 3

IndexColumns | TableName | TABLENAME | TABLE_NAME | 4

IndexColumns | | COLUMNNAME | COLUMN_NAME | 5

| | | | 1

| | | INDEX_NAME | 2

| TableOwner | TABLEOWNER | TABLE_OWNER | 3

| TableName | TABLENAME | TABLE_NAME | 4

| | | | 1

| | PACKAGENAME | OBJECT_NAME | 2

PackageBodies | | | | 1

PackageBodies | | | OBJECT_NAME | 2

| | | | 1

| | PACKAGENAME | PACKAGE_NAME | 2

| ObjectName | OBJECTNAME | OBJECT_NAME | 3

| ArgumentName | ARGUMENTNAME | ARGUMENT_NAME | 4

| | | | 1

| | | OBJECT_NAME | 2

UniqueKeys | | | | 1

UniqueKeys | Table_Name | TABLENAME | TABLE_NAME | 2

UniqueKeys | Constraint_Name | CONSTRAINTNAME | CONSTRAINT_NAME | 3

PrimaryKeys | | | | 1

PrimaryKeys | Table_Name | TABLENAME | TABLE_NAME | 2

PrimaryKeys | Constraint_Name | CONSTRAINTNAME | CONSTRAINT_NAME | 3

ForeignKeys | Foreign_Key_Owner | OWNER | FKCON.OWNER | 1

ForeignKeys | Foreign_Key_Table_Name | TABLENAME | FKCON.TABLE_NAME | 2

ForeignKeys | Foreign_Key_Constraint_Name | CONSTRAINTNAME | FKCON.CONSTRAINT_NAME | 3

ForeignKeyColumns | Owner | OWNER | FKCOLS.OWNER | 1

ForeignKeyColumns | Table_Name | TABLENAME | FKCOLS.TABLE_NAME | 2

ForeignKeyColumns | Constraint_Name | CONSTRAINTNAME | FKCOLS.CONSTRAINT_NAME | 3

0
source

All Articles