Reputation: 13
public static IEnumerable<Student> GetStudents()
{
List<Student> students = (List<Student>)HttpContext.Current.Cache.Get("GetAllStudentWithImg");
if (students!= null)
{
return students ;
}
students = new List<Student>();
using (PrincipalContext context = GetPrincipalContext())
{
using (UserPrincipal uprinc = new UserPrincipal(context))
{
using (PrincipalSearcher psearcher = new PrincipalSearcher(uprinc))
{
students = psearcher.FindAll()
.Select(x => new Student((DirectoryEntry)x.GetUnderlyingObject()))
.ToList();
}
}
}
HttpContext.Current.Cache.Add("GetAllStudentWithImg", students, null,
DateTime.UtcNow.AddMinutes(60),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Normal, null);
return students;
}
I created this function to get values from my database and it work but it load slowly, the pictures are not that many or big, so its not the content, I wonder if someone want to help me with improving my code?
Upvotes: 0
Views: 224
Reputation: 4513
Check this, comparision between findall and where: C# FindAll VS Where Speed.
Beside that, why don't you use inheritance between these PrincipalContext,UserPrincipal and PrincipalSearcher?
Upvotes: 1
Reputation: 646
FindAll() is not a Linq method. It's List(Of T) method and as such, it does not have Deffered execution as opposed to Where() which is Linq and supports deferred execution.
Upvotes: 0
Reputation: 1795
I do not see all your code, the code where you query to the database is not displayed, but I think the problem is here:
psearcher.FindAll().Select( ....
FindAll()
returns all records in the database table, after this you select what you need in your collection.
The better performance solution is: to query to the database only what you need.
then do not FIND ALL data, but find only what you need
Upvotes: 1