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:
//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))
if (column != null)
PKProperty = info;
if (PKProperty == null)
throw new NotSupportedException(
typeof(T).ToString() + " has no Primary Key");
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