是否有一个简短的方法可以通过Entity Framework找出某个实体是否属于父级?
有一些表,例如:Manager-> Project-> Document。
假设此链较长,并且有许多不同的链。我可以编写一种通用方法来检查链中的最后一个子项是否属于父级(链中的第一个表)吗?
在此示例中-检查文档是否属于Manager。可能需要递归函数吗?
答案 0 :(得分:1)
假设我们有这样的模型并且LazyLoading
已启用,请尝试this solution:
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");