Programmatically obtain Foreign keys between POCOs in Entity Framework 6(以编程方式获取实体框架 6 中 POCO 之间的外键)
问题描述
我面临一个 EF6 Code First 上下文,其中有几个 DbSet
的 POCO 在它们之间具有导航属性(和外键),例如:
I am faced with an EF6 Code First context, with a few DbSet
s 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
指向 Person
的 Id
属性?
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 之间的外键
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01