Question

I have a table with Departments and it has data as follows.

  • Admin
  • Support
  • Customer Care
  • etc...

The table is designed as follows

[ ID | User Name | Department | IsActive | ...]

When I am querying this table, what i want to return from the database depends on the currently logged in users' department.

  • Admin can view all
  • Support can't view admin but can view everything else
  • Customer care can't view support or admin but everything below.

If this database design is not sufficient, then please suggest me a good design.

What I have implemented so far is

var accountRepository = DataRepositoryFactory.GetDataRepository<IAccountRepository>();

  var accounts = accountRepository.Get() as List<UserManagement>;

  if (accounts != null)
   {
      if (AuthorizationAccount.Department == (SecurityConstants.RoleSuperAdministrator))
            return accounts.ToArray();
      else if (AuthorizationAccount.Department == (SecurityConstants.RoleAdministrator))
            return accounts.Where(r => !r.Department.Equals(SecurityConstants.RoleSuperAdministrator)).ToArray();
      else if (AuthorizationAccount.Department != (SecurityConstants.RoleAdministrator)
            || AuthorizationAccount.Department != (SecurityConstants.RoleSuperAdministrator))
            return accounts.Where(r => !r.Department.Equals(SecurityConstants.RoleSuperAdministrator))
                .Where(r => !r.Department.Equals(SecurityConstants.RoleAdministrator)).ToArray();
                }

  return null;

I don't like having so many IF conditions and it is a maintenance nightmare if the requirements gets changed or if the rules get more complex.

What are good design suggestions to implement this behavior better with less hardcoding?

Are there any design patterns to answer this type of problem?

Was it helpful?

Solution

You have 2 options:

  1. Specification pattern. Specification pattern is well describe in the internet. Here is the good description. I'd favour specification, but this is not always convenient.

  2. Filter out data on DbContext level (presuming Entity Framework is used). Head here for code and explanation how to implement this. This applies global filtering on low level, so you would not even have to think about it in your repository. But this adds unwanted coupling between your db-code and UI-code. Also increases complexity and adds debugging issues. Use this if your DbContext is not used anywhere else, other than MVC project.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top