Skip to content

Instantly share code, notes, and snippets.

@vsviridov
Created August 2, 2012 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vsviridov/3241061 to your computer and use it in GitHub Desktop.
Save vsviridov/3241061 to your computer and use it in GitHub Desktop.
Crappy way to detect Primary Keys in EF4
//Get all fields marked as Primary Key
var keyFields = type.GetProperties()
.Where(prop => prop.GetCustomAttributes(typeof(KeyAttribute), true).Any())
.Select(prop => prop.Name)
.ToList();
//Get all fields that end with Id and Not marked as Foreign Key
keyFields.AddRange(type.GetProperties()
.Where(prop =>
prop.Name.EndsWith("Id", true, CultureInfo.InvariantCulture)
&& !prop.GetCustomAttributes(typeof(ForeignKeyAttribute), true).Any()
)
.Select(prop => prop.Name));
//Remove all keys which have their FK attribute on the Navigation Property
var fkMiss = type.GetProperties()
.Where(prop => !prop.Name.EndsWith("Id", StringComparison.InvariantCultureIgnoreCase))
.Select(prop => Attribute.GetCustomAttributes(prop, typeof(ForeignKeyAttribute)).Cast<ForeignKeyAttribute>().Select(x => x.Name).ToList()).SelectMany(x => x).ToList();
keyFields = keyFields.Except(fkMiss).ToList();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment