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 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 指向 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 之间的外键
基础教程推荐
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 如果条件可以为空 2022-01-01
- 将数据集转换为列表 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 获取C#保存对话框的文件路径 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
