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 之间的外键
基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01