I am trying to use Entity Framework's MetadataWorkspace
to figure out the ID Foreign Key of a navigation property. My model looks like this:
public class Person
{
[Key]
public int PersonId { get; set; }
public int AddressId { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
public Address()
{
People = new HashSet<Person>();
}
[Key]
public int AddressId { get; set; }
public virtual ICollection<Person> People { get; set; }
}
class PersonDbContext : DbContext
{
public DbSet<Person> People { get; set; }
public DbSet<Address> Addresses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Person>()
.HasRequired(p => p.Address)
.WithMany(a => a.People)
.HasForeignKey(p => p.AddressId);
}
}
I have read other questions here on the subject: 1 2
They both suggest using the NavigationProperty.GetDependentProperties()
method, but I can't get it to return anything:
var context = new PersonDbContext();
var objectContext = ((IObjectContextAdapter) context).ObjectContext;
var metadata = objectContext.MetadataWorkspace;
var navProperties = metadata.GetItems<EntityType>(DataSpace.OSpace)
.SelectMany(e => e.NavigationProperties)
.ToList();
// navProperties.Count = 2 (Person.Address and Address.People)
var depProperties = navProperties
.SelectMany(p => p.GetDependentProperties())
.ToList();
// depProperties.Count = 0 :(
I've made sure to configure the context to explicitly state the fact that Person.AddressId
is the foreign key for the Person.Address
property. What am I missing here?