简体   繁体   English

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

[英]Retrieve table relationships from MS Access DB using C#

I am using C# with MS Access 2010. I need to retrieve the table relationships from the DB in order to determine the relationships between entities and use them in my C# code. 我在MS Access 2010中使用C#。我需要从数据库中检索表关系,以便确定实体之间的关系,并在我的C#代码中使用它们。 I need the same functionality for SQL Server database also. 我还需要SQL Server数据库相同的功能。

Is there a way to do this using C# and .NET 3.0/ 3.5/ 4.0? 有没有一种方法可以使用C#和.NET 3.0 / 3.5 / 4.0?

Appreciate your time. 感谢您的时间。

Thanks, Mahesh 谢谢,Mahesh

This is the code I used to retrieve the foreign key constraints (the relationships, if you prefer). 这是我用来检索外键约束(关系,如果您愿意的话)的代码。 TableSchema , ForeignKey and ForeignKeyColumn are my own classes, where I store the result. TableSchemaForeignKeyForeignKeyColumn是我自己的类,在其中存储结果。 The point is to use the GetOleDbSchemaTable method of the OleDbConnection : 关键是要使用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);
        }
    }
}

I would use DAO, in which case the relationships are in a collection that you can retrieve from the Relationships property of the Database object. 我将使用DAO,在这种情况下,关系位于可以从Database对象的Relationships属性检索的集合中。

In ADO.NET, you use the Relations property of the DataSet class. 在ADO.NET中,您可以使用DataSet类的Relations属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM