static void Main() { var context = new AdsEntities1(); //With no include //foreach (var ad in context.Ads) //{ // Console.WriteLine("Title : {0}; Status: {1}; Category: {2}; Town: {3}; User: {4};", // ad.Title, // ad.AdStatus.Status, // ad.Category != null ? ad.Category.Name : "null", // ad.Town != null ? ad.Town.Name : "null", // ad.AspNetUser); //} //With include //var ads = context.Ads // .Include(ad => ad.AdStatus) // .Include(ad => ad.Category) // .Include(ad => ad.Town); //foreach (var ad in ads) //{ // Console.WriteLine("Title : {0} Status: {1} Category: {2} Town: {3} User: {4}", // ad.Title, // ad.AdStatus.Status, // ad.Category != null ? ad.Category.Name : "null", // ad.Town != null ? ad.Town.Name : "null", // ad.AspNetUser); //} //With select var selectedAds = context.Ads.Select(ad => new { ad.Title, CurrentStatus = ad.AdStatus.Status, CategoryName = ad.Category.Name, TownName = ad.Town.Name, ad.AspNetUser }); foreach (var ad in selectedAds) { Console.WriteLine("Title : {0} Status: {1} Category: {2} Town: {3} User: {4}", ad.Title, ad.CurrentStatus, ad.CategoryName, ad.TownName, ad.AspNetUser); } }
static void Main() { var context = new AdsEntities1(); var stopWatch = new Stopwatch(); stopWatch.Start(); NotOptimizedMethod(context); Console.WriteLine("Not optimized method: {0}", stopWatch.Elapsed); stopWatch.Restart(); OptimizedMethod(context); Console.WriteLine("Optimized method: {0}", stopWatch.Elapsed); }
static void Main() { var context = new AdsEntities1(); var stopWatch = new Stopwatch(); var count = context.Ads; CleanCache(context); stopWatch.Start(); SelectEverything(context); Console.WriteLine("Not optimized method: {0}", stopWatch.Elapsed); CleanCache(context); stopWatch.Restart(); SelectCertainColumns(context); Console.WriteLine("Optimized method: {0}", stopWatch.Elapsed); }
private static void OptimizedMethod(AdsEntities1 context) { var ads = context.Ads .Where(c => c.AdStatus.Status == "Published") .Select(ad => new { Title = ad.Title, Category = ad.Category, Town = ad.Town, PublishDate = ad.Date }) .ToList() .OrderBy(ad => ad.PublishDate); //foreach (var ad in ads) //{ // Console.WriteLine("Title {0}; Category {1}; Town {2};", ad.Title, ad.Category != null ? ad.Category.Name : "null", ad.Town != null ? ad.Category.Name : "null"); //} }
private static void SelectEverything(AdsEntities1 context) { var selectAll = context.Ads.ToList(); }
private static void SelectCertainColumns(AdsEntities1 context) { var selectTitle = context.Ads.Select(ad => ad.Title).ToList(); }
private static void CleanCache(AdsEntities1 context) { context.Database.ExecuteSqlCommand("CHECKPOINT; DBCC DROPCLEANBUFFERS DBCC FREEPROCCACHE"); }