0

I have a table (Code first, EF6, Sql Server):

public int Srl { get; set; }
public StringName{ get; set; }
public Nullable<int> Parent { get; set; }

I want to delete a row in table with special Srl and all of child of that. Note that the child of a row may be something like:

row->
    Child1->
            Child1-1
    Child2->
    Child3->
           Child3-1
           Child3-2->
                   Child3-2-1
    Child4

I write this method:

private void DeleteObjectAndChildren(int id)
        {
            var menu = db.Menus.Where(m => m.Parent == id).ToList();
            foreach (var item in menu)
            {
                var child = db.Menus.Where(m => m.Parent == item.Srl).ToList();

                if (child.Count != 0)
                {
                    DeleteObjectAndChildren(item.Srl);
                }
                else
                {
                    db.Menus.Remove(item);
                }
            }
            db.SaveChanges();
        }

The code running without error but nothing change in database. Any body know whats my wrong?

And could anyone suggest better way to delete a row and all of child of that?

Ali
  • 3,373
  • 5
  • 42
  • 54
  • Can you post the full entity model in question? The way it is now (w/o any navigation property), I don't see how you can define the relationship. – Ivan Stoev Sep 22 '17 at 09:13

1 Answers1

1

One of the methods, you can delete it after you find the children.

MyDbContext db = new MyDbContext();
public List<Menus> GetChildren(int id)
{
    return db.Menus.Where(i => i.Parent == id || i.Id == id).ToList().Union(db.Menus.Where(i => i.Parent == id).ToList().SelectMany(i => GetChildren(i.Id)).ToList()).ToList();            
}
public void DeleteMenus(int id)
{
    GetChildren(id).ForEach(i => db.Entry(i).State = System.Data.Entity.EntityState.Deleted);
    db.SaveChanges();
}
neer
  • 4,031
  • 6
  • 20
  • 34