【问题标题】:Retrieve table relationships from MS Access DB using C#使用 C# 从 MS Access DB 中检索表关系
【发布时间】:2011-11-11 21:10:32
【问题描述】:

我在 MS Access 2010 中使用 C#。我需要从数据库中检索表关系以确定实体之间的关系并在我的 C# 代码中使用它们。 我也需要 SQL Server 数据库的相同功能。

有没有办法使用 C# 和 .NET 3.0/ 3.5/ 4.0 做到这一点?

珍惜你的时间。

谢谢, 马赫什

【问题讨论】:

    标签: c# sql-server ms-access relationship


    【解决方案1】:

    这是我用来检索外键约束(关系,如果您愿意的话)的代码。 TableSchemaForeignKeyForeignKeyColumn 是我自己的类,我将结果存储在其中。重点是使用OleDbConnectionGetOleDbSchemaTable方法:

    private static void RetrieveForeignKeyInfo(OleDbConnection cnn, TableSchema tableSchema, Func<string, string> prepareColumnNameForMapping)
    {
        string[] fkRestrictions = new string[] { null, null, null, null, null, tableSchema.TableName };
        using (DataTable dtForeignKeys = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Foreign_Keys, fkRestrictions)) {
            ForeignKey foreignKey = null;
            string constraintName = "";
            foreach (DataRow row in dtForeignKeys.Rows) {
                string newConstraintName = (string)row["FK_NAME"];
                if (newConstraintName != constraintName) {
                    constraintName = newConstraintName;
                    foreignKey = new ForeignKey();
                    foreignKey.MasterTableName = (string)row["PK_TABLE_NAME"];
                    tableSchema.ForeignKeys.Add(foreignKey);
                }
                var foreignKeyColumn = new ForeignKeyColumn();
                foreignKeyColumn.DetailColumnName = (string)row["FK_COLUMN_NAME"];
                foreignKeyColumn.MasterColumnName = (string)row["PK_COLUMN_NAME"];
                foreignKeyColumn.DetailColumnNameForMapping = prepareColumnNameForMapping(foreignKeyColumn.DetailColumnName);
                foreignKeyColumn.MasterColumnNameForMapping = prepareColumnNameForMapping(foreignKeyColumn.MasterColumnName);
                foreignKey.Columns.Add(foreignKeyColumn);
            }
        }
    }
    

    【讨论】:

    • 你的意思是在TableSchema类中存储一些SQL查询的结果吗?如果是这样,我没有需要外键关系的特定数据块。我需要检索数据库架构中存在的所有外键关系。
    • 我的示例检索一个表的外键。表名在 fkRestrictions 中指定。您没有 TableSchema 类。 TableSchema 和 ForeignKey 是我为我的目的而创建的类。您将从 cnn.GetOleDbSchemaTable() 调用中获得一个 DataTable。您可以尝试为表名传递 null,也可以使用返回所有可用表的模式表。看看 OleDbSchemaGuid 类。有很多可用的模式表,每个表都返回有价值的信息。
    【解决方案2】:

    我会使用 DAO,在这种情况下,关系位于一个集合中,您可以从 Database 对象的 Relationships 属性中检索该集合。

    在 ADO.NET 中,您使用 DataSet 类的 Relations 属性。

    【讨论】:

    • 我将 DAO 用于 Access DB。但是我应该为 SQL Server DB 做什么? DataSet.Relations 无济于事,因为我想要所有的外键关系。我没有需要找出关系的特定数据集。
    • 不能获取SqlDataAdapter,调用FillSchema获取DataSet中的schema吗?
    • 再次,我需要查询 SqlDataAdapter。我的数据库中有近 80 个表,我需要在没有实际数据的情况下检索外键关系。
    猜你喜欢
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 2010-12-14
    • 1970-01-01
    • 2017-12-22
    相关资源
    最近更新 更多