Easily find any table's Primary Key property
In my search for a universal generic Get() accessor for Linq-to-SQL DataContexts, I figured I would have to dynamically find the primary key of a table.
Using Reflection and the Attributes applied to L2S tables, it is not difficult at all:
It's just that easy, it will throw a NotSupportedException if there is no primary key, or the primary key allows NULL. It uses the Linq-to-SQL ColumnAttribute properties to determine what the primary key is. If there is more than one primary key, it will just use the first one it comes across.
The complete source code can be browsed at my new Utilities Library along with full documentation on CodePlex, just figured it would be easy to keep all of my utilities in one place. Otherwise, here is the meat of the code:
And yes, I did come up with a universal generic Get() accessor for Linq-to-SQL DataContexts, that's next post... or the code is already posted in my Utilities Library.
//get the primary key PropertyInfo table 'Product' PropertyInfo info = GetPrimaryKey<Product>();
It's just that easy, it will throw a NotSupportedException if there is no primary key, or the primary key allows NULL. It uses the Linq-to-SQL ColumnAttribute properties to determine what the primary key is. If there is more than one primary key, it will just use the first one it comes across.
The complete source code can be browsed at my new Utilities Library along with full documentation on CodePlex, just figured it would be easy to keep all of my utilities in one place. Otherwise, here is the meat of the code:
public static PropertyInfo GetPrimaryKey<T>() { PropertyInfo[] infos = typeof(T).GetProperties(); PropertyInfo PKProperty = null; foreach (PropertyInfo info in infos) { var column = info.GetCustomAttributes(false) .Where(x => x.GetType() == typeof(ColumnAttribute)) .FirstOrDefault(x => ((ColumnAttribute)x).IsPrimaryKey && ((ColumnAttribute)x).DbType.Contains("NOT NULL")); if (column != null) { PKProperty = info; break; } if (PKProperty == null) { throw new NotSupportedException( typeof(T).ToString() + " has no Primary Key"); } return PKProperty; }
And yes, I did come up with a universal generic Get() accessor for Linq-to-SQL DataContexts, that's next post... or the code is already posted in my Utilities Library.