编程方式获取波苏斯之间的外键的实体框架6 [英] Programmatically obtain Foreign keys between POCOs in Entity Framework 6

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

问题描述

我面对一个EF6代码优先的背景下,与他们之间的一些 DbSet 取值波苏斯的具有导航性能(和外键),例如:

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的属性/领域通过反射和猜测)以编程方式确定地址有一个 FK_PersonId 指向 ID

推荐答案

财产要获取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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆