简体   繁体   English

在 Entity Framework Core 中获取导航属性

[英]Get navigation properties in Entity Framework Core

In EF6, this method works to retrieve an entity's navigation properties:在 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 however does not exist in EF Core.然而, IObjectContextAdapter在 EF Core 中不存在。 Where should I be looking to get the list of navigation properties of an entity?我应该在哪里寻找实体的导航属性列表?

Fortunately, access to the model data has become a lot easier in Entity Framework core. 幸运的是,在Entity Framework核心中访问模型数据变得更加容易。 This is a way to list entity type names and their navigation property infos: 这是一种列出实体类型名称及其导航属性信息的方法:

using Microsoft.EntityFrameworkCore;
...

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

... where db is a context instance. ...其中db是一个上下文实例。

You would probably like to use the overload GetEntityTypes(typeof(T)) . 您可能希望使用重载GetEntityTypes(typeof(T))

EF core 6+英孚核心 6+

This works for me:这对我有用:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Fare>().Navigation(f => f.Extras).AutoInclude();
}

Ref: https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager#model-configuration-for-auto-including-navigations参考: https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager#model-configuration-for-auto-including-navigations

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM