Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NavigationProperty.GetDependentProperties() returns an empty collection

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?

like image 383
Alex Avatar asked Dec 04 '25 14:12

Alex


1 Answers

I've figured it out - I was using DataSpace.OSpace to retrieve the navigation properties. Instead I should have used DataSpace.CSpace, which is the conceptual model which contains the foreign key mappings.

like image 139
Alex Avatar answered Dec 07 '25 19:12

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!