Using Include(…) method only one SQL query with join is made to get the related entities
No additional SQL queries are made here for the related entities
Incorrect Use of ToList
In EF invoking ToList() executes the underlying SQL query in the database
Transforms IQueryable to List
Invoke ToList() as late as possible, after all filtering, joins and groupings
Avoid such code:
This will cause all order details to come from the database and to be filtered later in the memory
List orderItemsFromTokyo =
northwindEntities.Order_Details.ToList().
Where(od => od.Product.Supplier.City == "Tokyo").ToList();
Deleting Entities
Deleting entities (slower):
Executes SELECT + DELETE commands
NorthwindEntities northwindEntities = new NorthwindEntities();
var category = northwindEntities.Categories.Find(46);
northwindEntities.Categories.Remove(category);
northwindEntities.SaveChanges();
Deleting entities with native SQL (faster):
Executes a single DELETE command
NorthwindEntities northwindEntities = new NorthwindEntities();
northwindEntities.Database.ExecuteSqlCommand(
"DELETE FROM Categories WHERE CategoryID = {0}", 46);