Programmatically obtain Foreign keys between POCOs

2019-02-26 01:40发布

I am faced with an EF6 Code First context, with a few DbSets of POCOs that have navigation properties (and foreign keys) between them, e.g.:

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

Given these types, is there any proper way (i.e. without resorting to iterating over the POCO properties/fields by reflection and "guessing") to programmatically determine that Address has an FK_PersonId pointing to the Id property of Person?

1条回答
唯我独甜
2楼-- · 2019-02-26 02:10

To get the FK property's names for an specific entity you can use this generic method:

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

And if you want the nav. property's names the only you need to do is this:

 //...
 var navProperties = set.EntitySet.ElementType.NavigationProperties.Select(np=>np.Name);
查看更多
登录 后发表回答