NavigationProperty.GetDependentProperties()返回一个空集合

时间:2015-02-21 14:04:58

标签: c# entity-framework metadata entity-framework-6

我正在尝试使用Entity Framework的MetadataWorkspace来计算导航属性的ID外键。我的模型看起来像这样:

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);
    }
}

我在这里已经阅读了有关此主题的其他问题: 1 2

他们都建议使用NavigationProperty.GetDependentProperties()方法,但我不能让它返回任何内容:

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 :(

我已确保配置上下文以明确说明Person.AddressIdPerson.Address属性的外键这一事实。我在这里缺少什么?

1 个答案:

答案 0 :(得分:5)

我已经弄清楚了 - 我正在使用DataSpace.OSpace来检索导航属性。相反,我应该使用DataSpace.CSpace,它是包含外键映射的概念模型。