在Entity Framework Core中获取导航属性

Gue*_*lla 6 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();
}
Run Code Online (Sandbox Code Playgroud)

IObjectContextAdapter但是在EF Core中不存在。我应该在哪里获取实体的导航属性列表?

Ger*_*old 6

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

using Microsoft.EntityFrameworkCore;
...

var modelData = db.Model.GetEntityTypes()
    .Select(t => new
    {
        t.ClrType.Name,
        NavigationProperties = t.GetNavigations().Select(x => x.PropertyInfo)
    });
Run Code Online (Sandbox Code Playgroud)

... db上下文实例在哪里。

您可能想使用重载GetEntityTypes(typeof(T))

  • 更确切地说,是“ FindEntityType(typeof(T))”。HNY! (2认同)