CodeSmith: Checking if a column is an identity field exception.

This post is mostly a self reminder but it may come useful if you’re using CodeSmith as well.
It is possible to check if a (schema)column is an identity field via ExtendedProperties property of the SchemaObjectBase class:


// Only for Sql Server
private bool IsIdentityColumn(ColumnSchema column)
{
   return (bool)column.ExtendedProperties[“CS_IsIdentity”].Value;
}


There is one exception though and that’s if you’re sending the column object through the TableSchema.ForeignKey[index].ForeignKeyMemberColumns or TableSchema.ForeignKeys[index].PrimaryKeyMemberColumns, meaning:


for(int i=0; i<MySourceTable.ForeignKeys.Count; i++)
{
   // Same thing about MySourceTable.ForeignKeys[i].PrimaryKeyMemberColumns…
   for (int j=0; j<MySourceTable.ForeignKeys[i].ForeignKeyMemberColumns.Count; j++)
   {
      if (IsIdentityColumn(MySourceTable.ForeignKeys[i].ForeignKeyMemberColumns[j])) // <– Exception Here.
      {
         //do some code
         
      }
   }   
}


The extended properties will NOT hold the key “CS_IsIdentity” and IsIdentityColumn will throw an exception (null reference). I’m still not sure if this is by design or not, so I’ll try to fish it out on from the net and update the post later on. 


The solution is simply working a little harder via TableSchema.Keys and than verify the type of the key (by PrimaryKeyTable and ForeignKeyTable properties).


update:
This is quite a dirty hack, but it works and I’m loving it (I don’t have to change a lot of code in a lot of different places) !  
I refactor the mehotd IsIdentityColumn so it will do the trick:


private bool IsIdentityColumn(ColumnSchema column)
{
   if (column.ExtendedProperties[“CS_IsIdentity”] == null)
      column = column.Table.Columns[column.Name];

   return (bool)column.ExtendedProperties[“CS_IsIdentity”].Value;
}


Back to code…