How to check if an object is a child or a child of a child

c# entity-framework-6

Question

I am coding a C# Web API 2 webservice where an object has a foreign key int reference to specify the parent object.

How is the best way to check that an object being edited is not a child of the same object, or is not a child of a child?

I am using EF6.

Here is an example of the DbSet object:

public class User : IDbSet, IParent
{
    [Key]
    public int id { get; set; }
    public string name { get; set; }
    public int parentId { get; set; }
}
1
0
2/15/2016 8:12:04 AM

Popular Answer

Add a Parent navigation property:

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

And then you can do your checks:

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

or:

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

This would need sanity checks not to make and endless loop depending on the data you may have, but you get the idea

You could also improve this by having also a Children property:

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

And on your model configuration:

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

So you could also check for children, not just "up the chain"

0
2/15/2016 8:29:12 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow