繁体   English   中英

使用实体框架检查层次结构中是否存在对象

[英]Check if object exists in the hierarchy using Entity Framework

我有以下实体框架类,其中有一列是同一个表中主键的外键:

[Table("Items")]
public class Item
{
    [Key]
    public long ItemID { get; set; }

    public string ItemName { get; set; }

    public long? ItemParentID { get; set; }

    [ForeignKey("ItemParentID")]
    public virtual Item Parent { get; set; }

    public virtual ICollection<Item> Children { get; set; }
}

上面的映射效果很好,我可以通过传递ItemParentID并选择 Items 来将Children属性中的所有子项设置到第 n 级。

在我的业务逻辑中,我有ParentItemIDChildItemID ,我必须检查ChildItemID是否存在于 ParentItemID 的Children项中层次结构中的任何位置,它可以出现在ParentItems -> Children and -> their Children and -> their Children etc .

我尝试了以下 lambda 表达式,但它仅适用于两个级别的子项:

ParentItem.Children.Contains(context.Items.Where(x => x.ItemID == ChildItem).FirstOrDefault())

我如何通过编写一个返回 bool 值的简单 LINQ 或 lambda 语句来实现这一点?

我编写了以下递归方法来解决这个问题:

public bool CheckIfChildItemExists(ICollection<Item> childItems, long childItemId)
{
    var isChildExisting = false;
    foreach (Item item in childItems)
    {
        if (item.Children.Contains(context.Items.Where(x => x.ItemID == childItemId && x.IsActive).FirstOrDefault()))
        {
            isChildExisting = true;
            return isChildExisting;
        }
        else
        {
            return CheckIfItemChildExists(item.Children, childItemId);
        }
    }
    return isChildExisting;
}

然后像这样调用它:

bool isAccessible = CheckIfChildItemExists(ParentItem.Children, childItemId);

最好的方法

无论您的对象是什么以及数据库中的哪个表,您唯一需要的是对象中的主键。

C# 代码

var dbValue = EntityObject.Entry(obj).GetDatabaseValues();
if (dbValue != null)
{
   exist
}

暂无
暂无

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

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