Learning EF from laziness and delayed loading (2), ef latency
By studying EF greedy loading and delayed loading yesterday, it is not difficult to find that delayed loading is still very useful, but the problem also arises. Sometimes we only need to load one entity, there is no need for external entities related to it. In this case, let's take a look at how EF works during Delayed loading.
Open profiler
Write a query at the entrance of the Main function and set a breakpoint at Console. Read ();.
static void Main(string[] args) { var context = new EFDbContext(); var user = context.Users.FirstOrDefault(a => a.Id == 1); Console.WriteLine(user.Name); Console.Read(); }
In the last row of profiler, you can view the SQL statement that EF generates.
That is to say, when we only need the attributes of the object, EF will not help us load external entities.
Next, modify the content in the Main function.
static void Main(string[] args) { var context = new EFDbContext(); var users = context.Users.FirstOrDefault(a => a.Id == 1); //var users = context.Users.Include("Articles").FirstOrDefault(a => a.Id == 1); Console.WriteLine(users.Name); foreach (var a in users.Articles) { Console.WriteLine(a.Title + "," + a.Category.Name + "\n"); } Console.WriteLine(users.Articles.Count() + "\n" + users.Categories.Count() + "\n"); Console.Read(); }
After one-step debugging and profiler observation, we found that delayed loading was found only when we needed an external entity.
Load with laziness
Conclusion;
Delayed loading is performed only when we need it. When we need to load a large number of foreign key objects, it will increase the number of reads to the database.
In this case, you can consider greedy loading.