2012-03-16 52 views

回答

1

此代碼是我的O/R映射器的一部分

private string RetrieveAutoNumberColumn(OleDbConnection cnn, TableSchema tableSchema) 
{ 
    OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + tableSchema.TableName + "] WHERE False", cnn); 
    DataTable dtSchema = adapter.FillSchema(new DataTable(), SchemaType.Source); 
    if (dtSchema == null) { 
     throw new UnimatrixMappingException("Table \"" + tableSchema.TableName + "\" not found. Connection = " + this._connectString); 
    } 
    string columnName = null; 
    for (int i = 0; i < dtSchema.Columns.Count; i++) { 
     if (dtSchema.Columns[i].AutoIncrement) { 
      columnName = dtSchema.Columns[i].ColumnName; 
      break; 
     } 
    } 
    return columnName; 
} 

像這樣創建

var cnn = new OleDbConnection(
    "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"C:\Data\MyDatabase.mdb\";OLE DB Services=-1"); 

連接,您可以檢索主鍵(這是不一定相同作爲自動編號欄)像這樣

private static void RetrievePrimaryKeyInfo(OleDbConnection cnn, TableSchema tableSchema, string[] restrictions) 
{ 
    using (DataTable dtPrimaryKeys = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, restrictions)) { 
     foreach (DataRow row in dtPrimaryKeys.Rows) { 
      string columnName = (string)row["COLUMN_NAME"]; 
      //TODO: Do something useful with columnName here 
     } 
    } 
} 

其中restrictions定義爲

string[] restrictions = new string[] { null, null, tableName }; 
相關問題