Programmatically obtain foreign keys between POCO in Entity Framework 6

I came across the EF6 Code First context with several DbSet POCOs that have navigation properties (and foreign keys) between them, for example:

 public partial class Person { public Guid Id { get; set; } public virtual ICollection<Address> Address { get; set; } } public partial class Address { public Guid Id { get; set; } public Guid FK_PersonId { get; set; } public virtual Person Person { get; set; } } modelBuilder.Entity<Person>() .HasMany (e => e.Address) .WithRequired (e => e.Person) .HasForeignKey (e => e.FK_PersonId) .WillCascadeOnDelete(false); 

Given these types, is there any proper way (i.e., not to iterate over the POCO properties / fields by reflection and guessing) to programmatically determine that Address has FK_PersonId pointing to the Id Person property?

+2
c # entity-framework foreign-keys ef-code-first poco
source share
1 answer

To get the FK property names for a specific object, you can use this general method:

 public IEnumerable<string> GetFKPropertyNames<TEntity>() where TEntity:class { using (var context = new YourContext()) { ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext; ObjectSet<TEntity> set = objectContext.CreateObjectSet<TEntity>(); var Fks = set.EntitySet.ElementType.NavigationProperties.SelectMany(n=>n.GetDependentProperties()); return Fks.Select(fk => fk.Name); } } 

And if you want nav. The names of the properties you need to do are as follows:

  //... var navProperties = set.EntitySet.ElementType.NavigationProperties.Select(np=>np.Name); 
+7
source share

All Articles