C# 如何以编程方式复制具有复合键的MS Access表架构?

C# 如何以编程方式复制具有复合键的MS Access表架构?,c#,ms-access,database-schema,composite-key,C#,Ms Access,Database Schema,Composite Key,假设源MS Access数据库有一个名为MyTable1的表。假设MyTable1有一个复合主键组合,由两个独立的字段Phone和City组成。现在,当我使用下面的代码进行复制时,它不会使City成为目标表中复合键的一部分。如何修复 ADOX.Table sourceTable = default(ADOX.Table); sourceTable = sourceCat.Tables[tableName.Trim()];

假设源MS Access数据库有一个名为MyTable1的表。假设MyTable1有一个复合主键组合,由两个独立的字段Phone和City组成。现在,当我使用下面的代码进行复制时,它不会使City成为目标表中复合键的一部分。如何修复

            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集合中