【问题标题】:Check if object exists in the hierarchy using Entity Framework使用实体框架检查层次结构中是否存在对象
【发布时间】:2019-12-26 13:00:11
【问题描述】:

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

[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 并选择项目,就可以将Children 属性中的所有子项目设置为第n 级。

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

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

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

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

【问题讨论】:

  • 您需要递归解析所有子子项。我通常只是创建一个静态辅助方法来执行不是 linq 的查询。 public Boolean GetChild(Item i){....}
  • @jdweng 是的,这是一种方法,但我希望在 Entity Framework 本身内有一个解决方案,因为它已经能够将所有子项提升到第 n 级,而无需拧任何复杂的递归 @987654331 @语句..
  • 为什么人们认为递归方法很复杂?

标签: c# entity-framework linq


【解决方案1】:

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

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);

【讨论】:

    【解决方案2】:

    最好的方法

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

    C#代码

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

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 2010-12-20
      • 2016-08-01
      • 2013-04-16
      • 2020-08-15
      相关资源
      最近更新 更多