3

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?

Community
  • 1
  • 1
Alex
  • 7,639
  • 3
  • 45
  • 58

1 Answers1

5

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.

Alex
  • 7,639
  • 3
  • 45
  • 58
  • Thanks a lot! I looked everywhere to finally find out here why does it return an empty collection: `((System.Data.EntityClient.EntityConnection)ctx.Connection).GetMetadataWorkspace().GetItems(DataSpace.SSpace).Where(s => s.BuiltInTypeKind == BuiltInTypeKind.EntityType).Cast().Single(m => m.Name.Split('.').Last() == typeof(TEntity).Name).NavigationProperties` I was using SSpace! – Bizhan Sep 08 '15 at 14:31