c# - 在 Entity Framework Core 中获取导航属性

标签 c# entity-framework-core

在 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/

相关文章:

c# - 用于获取包含 SQL IN() 的 EF 的 LINQ 的表达式,其中实体子属性等于值

c# - 使用接口(interface)将对象从一种类型转换为另一种类型?

c# - 是否可以在不使用 MVC 的情况下访问 DisplayName 属性?

c# - Entity Framework 核心 : SqlException: A transport-level error has occurred when receiving results from the server

c# - ASP.NET Core Entity Framework Core 找不到 IndexAttribute

entity-framework-core - 核心 2 保持领域模型与数据库变化同步

c# - 在代码隐藏中绑定(bind)动态创建的控件

c# - Berkeley Packet Filter 到高级过滤表达式

c# - 在另一个表单上更改文本框的文本

c# - Entity Framework Core 2.0 Add-Migration 不创建任何迁移文件