c# - 使用 C# 从 MS Access DB 检索表关系

标签 c# sql-server ms-access relationship

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

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

感谢您的时间。

谢谢, 马赫什

最佳答案

这是我用来检索外键约束(关系,如果您愿意的话)的代码。 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);
        }
    }
}

关于c# - 使用 C# 从 MS Access DB 检索表关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8100018/

相关文章:

c# - App.Config 错误 "Configuration system failed to initialize"

sql-server - Visual Studio 2008 中的 "This server version is not supported.Only Up To Microsoft SQL server 2005 are supported"无法连接到 SQL Server 2008 R2

c# - 如何准确地将 sql 脚本插入到 Sql Server 表中

sql - MS Access Query 不使用标准相等运算符区分平假名和片假名

c# - 为什么 C# 4.0 中的可选参数需要编译时常量?

C# TreeView 并绑定(bind)到数据库

c# - 如何在 C# 中使用 FtpWebRequest 设置端口号?

sql-server - SQL转换日期时间并减去小时

mysql - 将 Access 查询中的文本框值转换为mysql

ms-access - Access 两个字符之间的字符串