以编程方式获取 Entity Framework 6 中 POCO 之间的外键

Programmatically obtain Foreign keys between POCOs in Entity Framework 6

我遇到了一个 EF6 Code First 上下文,其中有几个 DbSets 的 POCO 在它们之间具有导航属性(和外键),例如:

public partial class Person
{
    public         Guid                 Id      { get; set; }
    public virtual ICollection<Address> Address { get; set; } 
}

public partial class Address
{
    public         Guid   Id          { get; set; }
    public         Guid   FK_PersonId { get; set; }
    public virtual Person Person      { get; set; }
}

modelBuilder.Entity<Person>()
    .HasMany            (e => e.Address)
    .WithRequired       (e => e.Person)
    .HasForeignKey      (e => e.FK_PersonId)
    .WillCascadeOnDelete(false);

给定这些类型,是否有任何正确的方法(即不求助于通过反射和 "guessing" 迭代 POCO properties/fields)以编程方式确定 Address 具有 FK_PersonId 指向 PersonId 属性?

要获取特定实体的 FK 属性 名称,您可以使用此通用方法:

public IEnumerable<string> GetFKPropertyNames<TEntity>() where TEntity:class
{
        using (var context = new YourContext())
        {
            ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
            ObjectSet<TEntity> set = objectContext.CreateObjectSet<TEntity>();
            var Fks = set.EntitySet.ElementType.NavigationProperties.SelectMany(n=>n.GetDependentProperties());
            return Fks.Select(fk => fk.Name);
        }
 }

如果你想要导航。 属性 的名字您唯一需要做的就是:

 //...
 var navProperties = set.EntitySet.ElementType.NavigationProperties.Select(np=>np.Name);