递归删除对象及其子对象

时间:2019-04-06 04:53:21

标签: c# asp.net asp.net-mvc

这是我的函数,该函数根据其parentId为我提供节点列表:

public List<RepositoriesListViewModel> GetChildren(string ParentId)
{
    List<RepositoriesListViewModel> data = new List<RepositoriesListViewModel>();
    List<RepositoriesListViewModel> initialData = new List<RepositoriesListViewModel>();
    var List = dbContext.Repositories.ToList();
    foreach (var item in List)
    {
        initialData.Add(new RepositoriesListViewModel
        {
            id = item.Id,
            parent = item.ParentId,
            ApplicationsId = item.ApplicationsId,
            text = item.Name,
            Path = item.Path,
            CreatedOn = item.CreatedOn
        });
    };
    foreach (RepositoriesListViewModel child in initialData.Where(x => x.parent == ParentId))
    {
        child.Children = GetChildren(child.id);
        data.Add(child);
    }
    return data;
}

我想知道是否也可以使用此功能删除项目及其子项?我要在哪里添加删除呼叫?

这是我的删除呼叫的样子:

public void Delete(string Input)
{
    try
    {
        var repo = Get(Input);
        dbContext.Repositories.Remove(repo);
        dbContext.SaveChanges();
        logger.LogInformation(LoggingGlobals.Delete + " Repository: " + repo.Name);
    }
    catch (Exception e)
    {
        logger.LogError(e, "Failed to delete Repository");
    }
}

1 个答案:

答案 0 :(得分:1)

似乎您想要这样的东西:

public void Delete(string Input)
{
    try
    {
        var children = GetChildren(Input);

        foreach(var child in children)
        {
            Delete(child.Id);
        }

        var repo = Get(Input);
        dbContext.Repositories.Remove(repo);
        dbContext.SaveChanges();
        logger.LogInformation(LoggingGlobals.Delete + " Repository: " + repo.Name);
    }
    catch (Exception e)
    {
        logger.LogError(e, "Failed to delete Repository");
    }
}

因此,在删除项目本身之前,首先要删除其子项及其子项。