Be careful about lazy loading. If that's enabled, you can end up with this error if you're doing something in a loop, for example.
One way to get around this, if you don't want to turn off lazy loading (and have to remember to turn it back on again, if you need it) is to use eager loading, which you do by adding the Include()
statement to your query. For example, if you have an entity called Contact
and a reference to a collection of Address
entities on a Contact
and you want to get the Addresses
for the Contacts
you're querying for, using this in your LINQ query
.Include("Addresses")
and this will load the Addresses
for each loaded Contact
via the generated query. Use Include()
sparingly on each query you want to use eager loading for though because there can be a performance hit.