Skip to content

Instantly share code, notes, and snippets.

@vsviridov
Created August 2, 2012 22:01
Show Gist options
  • Select an option

  • Save vsviridov/3241061 to your computer and use it in GitHub Desktop.

Select an option

Save vsviridov/3241061 to your computer and use it in GitHub Desktop.

Revisions

  1. vsviridov created this gist Aug 2, 2012.
    18 changes: 18 additions & 0 deletions ef4_pk_detect.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    //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();