Created
August 2, 2012 22:01
-
-
Save vsviridov/3241061 to your computer and use it in GitHub Desktop.
Crappy way to detect Primary Keys in EF4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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