我正在尝试使用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);
}
}
他们都建议使用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.AddressId
是Person.Address
属性的外键这一事实。我在这里缺少什么?
答案 0 :(得分:5)
我已经弄清楚了 - 我正在使用DataSpace.OSpace
来检索导航属性。相反,我应该使用DataSpace.CSpace
,它是包含外键映射的概念模型。