c# - 包括所有具有递归属性的导航属性 EF Core
问题描述
我试图急切地加载与实体相关的所有数据,但我仍然对像这样的递归属性有疑问:
public class Node : BaseAbstractEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
[ForeignKey("TypeId")]
public virtual NodeType Type { get; set; }
public int? TypeId { get; set; }
[ForeignKey("ParentId")]
public virtual Node Parent { get; set; }
public int? ParentId { get; set; }
public ICollection<Node> Children { get; set; }
}
我在这种方法中使用它:
public async Task<object> JustGetAsync(Type type, JObject value, DbContext context)
{
int id = 0;
if (value != null && value["id"] != null)
id = Int32.Parse(value["id"].ToString());
if (id != 0)
return await context.FindAsync(type, id);
var TypeSet = (IQueryable<object>) context.GetType()
.GetMethod("Set")
.MakeGenericMethod(type)
.Invoke(context, null);
return await TypeSet.Include(context.GetIncludePaths(type)).ToListAsync();
}
get IncludePaths 是我在此处找到的代码 在此处输入链接描述,有助于渴望所有属性:
public static IQueryable Include(this IQueryable source, IEnumerable navigationPropertyPaths) where T : class { return navigationPropertyPaths.Aggregate(source, (query, path) => query.Include(path)); }
public static IEnumerable<string> GetIncludePaths(this DbContext context, Type clrEntityType)
{
var entityType = context.Model.FindEntityType(clrEntityType);
var includedNavigations = new HashSet<INavigation>();
var stack = new Stack<IEnumerator<INavigation>>();
while (true)
{
var entityNavigations = new List<INavigation>();
foreach (var navigation in entityType.GetNavigations())
{
if (includedNavigations.Add(navigation))
entityNavigations.Add(navigation);
}
if (entityNavigations.Count == 0)
{
if (stack.Count > 0)
yield return string.Join(".", stack.Reverse().Select(e => e.Current.Name));
}
else
{
foreach (var navigation in entityNavigations)
{
var inverseNavigation = navigation.FindInverse();
if (inverseNavigation != null)
includedNavigations.Add(inverseNavigation);
}
stack.Push(entityNavigations.GetEnumerator());
}
while (stack.Count > 0 && !stack.Peek().MoveNext())
stack.Pop();
if (stack.Count == 0) break;
entityType = stack.Peek().Current.GetTargetType();
}
}
解决方案
推荐阅读
- google-maps - 为什么 Google 地图 API 结果不准确?
- php - PHP中if条件变量前为什么要用@
- android - Firebase 服务器已终止移动网络上的上传会话
- mysql - Mysql 字符串连接仅当值存在时
- javascript - 通过自分配键防止组件重用?
- python - 更新滑块值不断使程序崩溃
- azure - 多因素身份验证注册重定向
- regex - 我们可以使用基于lookbehinds的条件吗?
- reactjs - 如何在 React 应用程序中使用 axios 响应解决 TypeScript 错误
- python - 如何在 Python lambda 中安装 TensorFlow Serving Client API?