簡體   English   中英

使用C#從MS Access DB檢索表關系

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

我在MS Access 2010中使用C#。我需要從數據庫中檢索表關系,以便確定實體之間的關系,並在我的C#代碼中使用它們。 我還需要SQL Server數據庫相同的功能。

有沒有一種方法可以使用C#和.NET 3.0 / 3.5 / 4.0?

感謝您的時間。

謝謝,Mahesh

這是我用來檢索外鍵約束(關系,如果您願意的話)的代碼。 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);
        }
    }
}

我將使用DAO,在這種情況下,關系位於可以從Database對象的Relationships屬性檢索的集合中。

在ADO.NET中,您可以使用DataSet類的Relations屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM