Does linq to sql automatically lazy load associate

2019-01-26 13:20发布

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条回答
ら.Afraid
2楼-- · 2019-01-26 13:35

Yes, lazy loading is enabled by default. Check out this article.

查看更多
Explosion°爆炸
3楼-- · 2019-01-26 13:50

Yes, I believe it does. It also has a "load with" feature/semantic that allows you to batch load several things in a shotgun approach. This is useful when you know you'll need related data along with the main entity right off the bat, like to pre-cache all the data you'll need to render a single Web Page etc.

查看更多
太酷不给撩
4楼-- · 2019-01-26 13:55

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.

查看更多
登录 后发表回答