以编程方式获取实体框架 6 中 POCO 之间的外键

Programmatically obtain Foreign keys between POCOs in Entity Framework 6(以编程方式获取实体框架 6 中 POCO 之间的外键)

本文介绍了以编程方式获取实体框架 6 中 POCO 之间的外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

鉴于这些类型,是否有任何适当的方法(即不诉诸通过反射和猜测"来迭代 POCO 属性/字段)以编程方式确定 Address 具有 FK_PersonId 指向 PersonId 属性?

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?

推荐答案

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

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

这篇关于以编程方式获取实体框架 6 中 POCO 之间的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:以编程方式获取实体框架 6 中 POCO 之间的外键