在 EF6 中,此方法用于检索实体的导航属性:
private List<PropertyInfo> GetNavigationProperties<T>(DbContext context) where T : class
{
var entityType = typeof(T);
var elementType = ((IObjectContextAdapter)context).ObjectContext.CreateObjectSet<T>().EntitySet.ElementType;
return elementType.NavigationProperties.Select(property => entityType.GetProperty(property.Name)).ToList();
}
IObjectContextAdapter
但是在 EF Core 中不存在。我应该在哪里寻找实体的导航属性列表?
最佳答案
幸运的是,在 Entity Framework Core 中访问模型数据变得更加容易。这是一种列出实体类型名称及其导航属性信息的方法:
using Microsoft.EntityFrameworkCore;
...
var modelData = db.Model.GetEntityTypes()
.Select(t => new
{
t.ClrType.Name,
NavigationProperties = t.GetNavigations().Select(x => x.PropertyInfo)
});
... 其中 db
是上下文实例。
您可能希望使用重载 GetEntityTypes(typeof(T))
。
关于c# - 在 Entity Framework Core 中获取导航属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48070880/