Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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