Let me offer my simple solution that fits needs to enable/disable the branch of hierarchical data of the selected department's structure of an organization.
The table Departments looks according this SQL
CREATE TABLE [dbo].[Departments](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](1000) NOT NULL,
[OrganizationID] [int] NOT NULL,
[ParentID] [int] NULL,
[IsEnabled] [bit] NOT NULL,
CONSTRAINT [PK_Departments] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
C# code provides a very simple approach that work fine for me.
1. It returns the complete table asynchronously.
2. It changes property for the linked rows.
public async Task<bool> RemoveDepartmentAsync(int orgID, int depID)
{
try
{
using (var db = new GJobEntities())
{
var org = await db.Organizations.FirstOrDefaultAsync(x => x.ID == orgID); // Check if the organization exists
if (org != null)
{
var allDepartments = await db.Departments.ToListAsync(); // get all table items
var isExisting = allDepartments.FirstOrDefault(x => x.OrganizationID == orgID && x.ID == depID);
if (isExisting != null) // Check if the department exists
{
isExisting.IsEnabled = false; // Change the property of visibility of the department
var all = allDepartments.Where(x => x.OrganizationID == orgID && x.ID == isExisting.ID).ToList();
foreach (var item in all)
{
item.IsEnabled = false;
RecursiveRemoveDepartment(orgID, item.ID, ref allDepartments); // Loop over table data set to change property of the linked items
}
await db.SaveChangesAsync();
}
return true;
}
}
}
catch (Exception ex)
{
logger.Error(ex);
}
return false;
}
private void RecursiveRemoveDepartment(int orgID, int? parentID, ref List<Department> items)
{
var all = items.Where(x => x.OrganizationID == orgID && x.ParentID == parentID);
foreach (var item in all)
{
item.IsEnabled = false;
RecursiveRemoveDepartment(orgID, item.ID, ref items);
}
}
This approach works very fast for relative small amount of records I guess less 100000.
Probably for big set of data you have to implement server side stored function.
Enjoy!