Guest User

Untitled

a guest
Aug 16th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. /// <summary>
  2. /// Provides a convention for fixing the independent association (IA) foreign key column names. (prevents EF from adding _Id)
  3. /// </summary>
  4. public class ForeignKeyNamingConvention : IStoreModelConvention<AssociationType>
  5. {
  6. public void Apply(AssociationType association, DbModel model)
  7. {
  8. // Identify a ForeignKey properties (including IAs)
  9. if (association.IsForeignKey)
  10. {
  11. // rename FK columns
  12. var constraint = association.Constraint;
  13. if (DoPropertiesHaveDefaultNames(constraint.FromProperties, constraint.ToRole.Name, constraint.ToProperties))
  14. {
  15. NormalizeForeignKeyProperties(constraint.FromProperties);
  16. }
  17. if (DoPropertiesHaveDefaultNames(constraint.ToProperties, constraint.FromRole.Name, constraint.FromProperties))
  18. {
  19. NormalizeForeignKeyProperties(constraint.ToProperties);
  20. }
  21. }
  22. }
  23.  
  24. private bool DoPropertiesHaveDefaultNames(ReadOnlyMetadataCollection<EdmProperty> properties, string roleName, ReadOnlyMetadataCollection<EdmProperty> otherEndProperties)
  25. {
  26. if (properties.Count != otherEndProperties.Count)
  27. {
  28. return false;
  29. }
  30.  
  31. for (int i = 0; i < properties.Count; ++i)
  32. {
  33. if (!properties[i].Name.EndsWith("_" + otherEndProperties[i].Name))
  34. {
  35. return false;
  36. }
  37. }
  38. return true;
  39. }
  40.  
  41. private void NormalizeForeignKeyProperties(ReadOnlyMetadataCollection<EdmProperty> properties)
  42. {
  43. for (int i = 0; i < properties.Count; ++i)
  44. {
  45. string defaultPropertyName = properties[i].Name;
  46. int ichUnderscore = defaultPropertyName.IndexOf('_');
  47. if (ichUnderscore <= 0)
  48. {
  49. continue;
  50. }
  51. string navigationPropertyName = defaultPropertyName.Substring(0, ichUnderscore);
  52. string targetKey = defaultPropertyName.Substring(ichUnderscore + 1);
  53.  
  54. string newPropertyName;
  55. if (targetKey.StartsWith(navigationPropertyName))
  56. {
  57. newPropertyName = targetKey;
  58. }
  59. else
  60. {
  61. newPropertyName = navigationPropertyName + targetKey;
  62. }
  63. properties[i].Name = newPropertyName;
  64. }
  65. }
  66.  
  67. }
Add Comment
Please, Sign In to add comment