Learning EF from laziness and delayed loading (2), ef latency

Source: Internet
Author: User

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.

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.