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;
 }
Malachi
29k11 gold badges86 silver badges188 bronze badges
asked Nov 23, 2013 at 17:39
\$\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.

answered Nov 24, 2013 at 1:24
\$\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\$ 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\$ Commented Nov 24, 2013 at 9:18

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.