2
\$\begingroup\$

Is there a simpler and optimized way to calculate listAdminCorePriveleges and privileges ?

public string[] GetPrivilegesForUserByPersonEntityId(int personEntityId)
    {
        var listPrivileges = new List<string>();
        var listAdminCorePriveleges = (_accountRepository.AsQueryable()
          .Where(acc => acc.PersonEntityId == personEntityId)
          .Select(acc => acc.AccountAdminPositionAssignments.Where(aap => aap.IsLocked == false && aap.IsObsolete == false).Select(aap => aap.AdminPosition.AdminType.AdminPrivileges))
          ).AsEnumerable();

        foreach (var adminCorePriveleges in listAdminCorePriveleges)
        {
            foreach (var adminCorePrivelege in adminCorePriveleges)
            {
                listPrivileges.Add(adminCorePrivelege.Name); 
            }
        }
        string[] privileges = listPrivileges.Distinct().ToArray();
        return privileges;
    }
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

To know for sure what exactly is inefficient you'd need to hook up a profiler.

Code wise you should be able to do it all in one query if I'm not mistaken:

return _accountRepository.AsQueryable()
            .Where(acc => acc.PersonEntityId == personEntityId)
            .SelectMany(acc => acc.AccountAdminPositionAssignments
                                  .Where(aap => !aap.IsLocked && !aap.IsObsolete)
                                  .SelectMany(aap => aap.AdminPosition.AdminType.AdminPrivileges.Select(p => p.Name)))
            .Distinct()
            .ToArray();

This will in theory also move the name selection and distinct filtering to the database which means that probably slightly less data has to be transferred. Adds a bit more work for the database server but that kind of stuff is what they should do well.

\$\endgroup\$
2
  • \$\begingroup\$ Is it good practice to write .Where(acc => acc.PersonEntityId == personEntityId && acc.AccountAdminPositionAssignments.Any(aap => !aap.IsLocked) && ...).SelectMany(acc => acc.AccountAdminPositionAssignments.SelectMany(aap => ... instead of yours? \$\endgroup\$
    – Iman
    Commented Nov 24, 2013 at 8:35
  • 1
    \$\begingroup\$ @Iman: Not really sure. I like to filter at the place where I'm selecting the data from, but if your version yields a better query or you simply like it better then go for it. \$\endgroup\$
    – ChrisWue
    Commented Nov 24, 2013 at 9:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.