首页 > 解决方案 > 可查询的没有获得导航属性

问题描述

我不知道我在这里没有得到什么,但导航属性没有使用 Inlucde 方法加载。

public IEnumerable<T> GetAll<T>() where T : class
    {
        List<string> navigationProperties =
     GetNavigationProperties<T>();

        var query = _context.Set<T>().AsQueryable();

        foreach (var navigationProperty in navigationProperties)
        {
            query.Include(navigationProperty);
        }

        return query.ToList();
    }


      private static List<string> GetNavigationProperties<T>() where T : class
    {
        return typeof(T).GetProperties()
            .Where(x => x.GetCustomAttributesData()
                .Any(p => p.AttributeType == typeof(NavigationPropertyAttribute)))
  .Select(n => n.Name).ToList();
    }

NavigationPropertyAttribute 是一个自定义属性,GetNavigationProperties() 方法返回指定类型的所有导航属性的列表,正如我在调试期间看到的那样。

标签: c#entity-framework

解决方案


您必须分配返回值 -Include()不是 void 类型

query = query.Include(navigationProperty);

推荐阅读