【发布时间】: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
我在 MS Access 2010 中使用 C#。我需要从数据库中检索表关系以确定实体之间的关系并在我的 C# 代码中使用它们。 我也需要 SQL Server 数据库的相同功能。
有没有办法使用 C# 和 .NET 3.0/ 3.5/ 4.0 做到这一点?
珍惜你的时间。
谢谢, 马赫什
【问题讨论】:
标签: c# sql-server ms-access relationship
这是我用来检索外键约束(关系,如果您愿意的话)的代码。 TableSchema、ForeignKey 和 ForeignKeyColumn 是我自己的类,我将结果存储在其中。重点是使用OleDbConnection的GetOleDbSchemaTable方法:
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 属性。
【讨论】: