簡體   English   中英

如何檢查物體是小孩還是小孩的孩子

[英]How to check if an object is a child or a child of a child

我正在編碼一個C#Web API 2 Web服務,其中一個對象具有一個外鍵int引用來指定父對象。

如何最好的方法來檢查正在編輯的對象不是同一對象的子對象,還是不是子對象的子對象?

我正在使用EF6。

這是DbSet對象的示例:

public class User : IDbSet, IParent
{
    [Key]
    public int id { get; set; }
    public string name { get; set; }
    public int parentId { get; set; }
}

添加Parent導航屬性:

public class User : IDbSet, IParent
{
    [Key]
    public int id { get; set; }
    public string name { get; set; }
    // notice that parent's id should be 
    // optional [at some point your parent will have to be null], 
    // thus we make the foreign key nullable
    public int? parentId { get; set; } 

    [ForeignKey("parentId")]
    public virtual User Parent { get; set; }
}

然后您可以進行檢查:

// I am not parent of myself
if(editedUser.Parent != editedUser) { ... }

要么:

bool AmIIntheChain()
{
  var curUserParent = editedUser.Parent;        
  while(curUserParent != null)
  {
   if(curUserParent == editedUser) 
      return false;
    curUserParent = curUserParent.Parent;
  }
  return true;
}

這可能需要進行健全性檢查,並根據您可能擁有的數據進行無休止的循環,但是您明白了

您還可以通過擁有Children屬性來改善這一點:

public class User : IDbSet, IParent
{
    [Key]
    public int id { get; set; }
    public string name { get; set; }
    public int? parentId { get; set; } 
    public virtual User Parent { get; set; }
    public virtual ICollection<User> Children { get;set; }
}

並在您的模型配置上:

modelBuilder.Entity<User>()
      .HasMany(t => t.Children)
      .WithOptional(t => t.Parent)
      .HasForeignKey(t => t.parentId);

因此,您還可以檢查孩子,而不僅僅是“上鏈”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM