Does linq to sql automatically lazy load associated entities?

前端 未结 3 2156
北海茫月
北海茫月 2020-12-19 08:54

Does linq to sql automatically lazy load associated entities?

I would think it would but I can\'t find an article stating it as such.

3条回答
  •  我在风中等你
    2020-12-19 09:39

    It depends how you define "lazy-load".

    If you say

    var person = (from p in db.People 
                  where p.PersonId = pid 
                  select p).First();
    var spouse = person.Spouse;   // based on the SpouseId FK 
                                  // back into the People table.
    

    Then that would be precisely "lazying loading" as the second object is not pulled from the database until it is referenced. This however, will require two database queries.

    However, if you were to say,

    var family = (from p in db.People
                  where p.PersonId = pid 
                 select new 
                  { 
                     Name = p.Name, 
                     SpouseName = p.Spouse.Name
                  }).First();
    

    Then Linq will automatically do the join and load the information from both records in a single database query.

提交回复
热议问题