gpt4 book ai didi

c# - Entity Framework 检查 child 是否属于 parent

转载 作者:太空宇宙 更新时间:2023-11-03 12:12:11 25 4
gpt4 key购买 nike

如果一个实体属于父实体,是否有一种简短的方法可以通过 Entity Framework 找出?

例如有一些表:Manager->Project->Document。

假设这条链更长并且有很多不同的链。我可以编写一种通用方法来检查链中的最后一个子项是否属于父项(链中的第一个表)吗?

在此示例中 - 检查 Document 是否属于 Manager。这可能需要递归函数吗?

最佳答案

尝试 this solution假设我们有这样的模型并且 LazyLoading 已打开:

public class Manager
{
public int Id { get; set; }
public virtual ICollection<Project> Projects { get; set; }
}

public class Project
{
public int Id { get; set; }
public virtual ICollection<Document> Documents { get; set; }
public virtual Manager Manager { get; set; }
public int? ManagerId { get; set; }
}

public class Document
{
public int Id { get; set; }
public virtual Project Project { get; set; }
public int? ProjectId { get; set; }
}

实现:

public static TParent FindParentOf<TParent, TChild>(TChild child)
where TParent : class
where TChild : class
{
return FindParentOfRecursive(child, typeof(TParent)) as TParent;
}

private static object FindParentOfRecursive(object child, Type parentType)
{
var IEnumType = typeof(IEnumerable);
var childType = child.GetType();
var strType = typeof(string);

foreach (var prop in childType.GetProperties()
.Where(x => x.PropertyType.IsClass && x.PropertyType != strType
&& !IEnumType.IsAssignableFrom(x.PropertyType)))
{
//calling to database via LazyLoading with query like:
//select top(1) * from dbo.Parents where Id = child.ParentId
var parentVal = prop.GetValue(child);

if (prop.PropertyType == parentType)
return parentVal;
else if(parentVal != null)
{
var result = FindParentOfRecursive(parentVal, parentType);
if (result != null)
return result;
}
}
return null;
}

用法:

var manager = FindParentOf<Manager, Document>(doc);
if(manager?.Id == lookingForManagerId)
Console.WriteLine("Belongs");

关于c# - Entity Framework 检查 child 是否属于 parent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51583931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com