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

标签 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 属性的外键这一事实。我在这里缺少什么?

最佳答案

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

关于c# - NavigationProperty.GetDependentProperties() 返回一个空集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28646687/

相关文章:

c# - 安全存储 Azure Key Vault clientSecret

c# - 带有 Mysql 和 NullReferenceException 的 Entity Framework 6

c# - Entity Framework Core 级联删除一对一关系

c# - Linq.Except函数 "At least one object must implement IComparable."

c# - .NET 中运行时对象的内存占用是多少?

c# - 当 DatabaseGenerated.Identity 已经与 Entity Framework 一起使用时自动增加一个数字

从 R 包描述中读取 Authors@R 字段作为向量

typescript - 如何正确扩展FormGroup

c++ - 从自己的程序中获取程序元数据

c# - Windows 8 metro : ListView ignores ItemTemplate