Sql – Determining a SQL Server Identity Column Name in .NET

linqlinq-to-sqlnetsql servervb.net

I'm trying to write some generic code in VB.NET that determines whether or not a SQL server database table contains an identity column and, if so, to return the name of that column.

I'm working in Visual Basic 2008 Express and have created a SQL database, "MyDatabase" with 1 table called "MyTable". Within that table, I've got 3 columns, "ID", "Column1" and "Column2". I know, I know… inventive names. Under column properties in the Database Explorer, I've set the "ID" column "Identity Specification" to "yes" and have set the "Is Identity" value to "yes".

I need for the .NET code to return "ID" as the identity column. Can this be done through LINQ or some other means?

Thanks very much in advance!

Luck

Best Answer

Use SQLDataReader to open MyTable (SELECT ID from myTable WHERE 1 = 2) & use GetSchemaTable method, which will give you the datatable.

As per the docs, check for the content of a column named IsAutoIncrement. If it returns true, it should be an Identity column.

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getschematable.aspx

Note: This is purely based on my memory & help from the MSDN docs.