Search code examples
c#linq-to-sql

linq to sql loadwith vs associatewith


What is the difference between loadwith and associatewith? From the articles I read, it seems that loadwith is used to load addition data (e.g. all orders for the customers), while AssociateWith is used to filter data.

Is that a correct understanding? It will be nice if someone can explain this with an example based explanation.


Solution

  • LoadWith is used to perform an eager load of an association as opposed to the default lazy load.

    Normally, associations are loaded the first time you reference them. That means if you select 100 Order instances, and then do something with each of their Details, you're actually performing 101 SELECT operations against the database. On the other hand, if the LoadOptions specify LoadWith<Order>(o => o.Details), then it's all done in a single SELECT with an added JOIN.

    AssociateWith doesn't have any effect on when the association is loaded, just what is loaded. It adds a WHERE clause every time you load an association.

    As you say, AssociateWith is used to automatically filter data. Typically you'd use this if you know that an association has a very large number of elements and you only need a specific subset of them. Again, it's mainly a performance optimization, just a different kind.