[英]How do I programmatically copy MS Access table schema which has composite key?
Let's say source MS Access database has a table called MyTable1. 假设源MS Access数据库有一个名为MyTable1的表。 And let's say MyTable1 has a composite primary key (Combination of two separate field Phone and City).
假设MyTable1有一个复合主键(两个单独的字段Phone和City的组合)。 Now when I copy using the following code, it does not make City as part of composite key in target table.
现在,当我使用以下代码复制时,它不会使City成为目标表中复合键的一部分。 How do fix
如何解决
ADOX.Table sourceTable = default(ADOX.Table);
sourceTable = sourceCat.Tables[tableName.Trim()];
ADOX.Table newTable = new ADOX.Table();
newTable.ParentCatalog = targetCat;
tempNewtableName = sourceCat.Tables[tableName.Trim()].Name;
newTable.Name = tempNewtableName;
ADOX.Column newCol = default(ADOX.Column);
DataTable primaryKeyDT = new DataTable();
primaryKeyDT.Columns.Add("FieldName");
primaryKeyDT.Columns.Add("Type");
foreach (ADOX.Index idx1 in sourceCat.Tables[tableName].Indexes)
{
if (idx1.PrimaryKey == true)
{
primaryKeyDT.Rows.Add(idx1.Columns[0].Name, idx1.Name);
}
}
foreach (ADOX.Column SourceCol in sourceTable.Columns)
{
newCol = new ADOX.Column();
newCol.Type = SourceCol.Type;
newCol.DefinedSize = SourceCol.DefinedSize;
newCol.ParentCatalog = targetCat;
newCol.Precision = SourceCol.Precision;
newCol.DefinedSize = SourceCol.DefinedSize;
newCol.Attributes = SourceCol.Attributes;
newCol.Name = SourceCol.Name;
newCol.NumericScale = SourceCol.NumericScale;
newTable.Columns.Append(newCol);
DataRow[] results = primaryKeyDT.Select("FieldName ='" + SourceCol.Name + "'");
if (results.Length > 0)
{
idx = new Index();
idx.Name = "idx_" + SourceCol.Name;
idx.PrimaryKey = true;
idx.Columns.Append(SourceCol.Name);
newTable.Indexes.Append(idx);
}
}
targetCat.Tables.Append(newTable);
您应该遍历results []并将每个字段添加到idx.Columns集合中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.