【问题标题】:Get navigation properties in Entity Framework Core在 Entity Framework Core 中获取导航属性
【发布时间】:2023-03-17 22:50:01
【问题描述】:

在 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 中不存在。我应该从哪里获取实体的导航属性列表?

【问题讨论】:

    标签: c# entity-framework-core


    【解决方案1】:

    幸运的是,在 Entity Framework 核心中访问模型数据变得更加容易。这是一种列出实体类型名称及其导航属性信息的方法:

    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))。

    【讨论】:

    • 或更准确地说,FindEntityType(typeof(T))。 HNY!
    • 我认为值得指出的是,EF Core 团队表示不建议在您的代码中直接使用FindEntityType(Type),因为它可能会发生变化。 Here's a link
    猜你喜欢
    • 1970-01-01
    • 2017-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多