简体   繁体   中英

remove row in parent-child table in Entity framework

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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