views:

353

answers:

1

I'm currently learning a bit more about Linq-To-Entities - particularly at the moment about eager and lazy loading.

proxy.User.Include("Role").First(u => u.UserId == userId)

This is supposed to load the User, along with any roles that user has. I have a problem, but I also have a question. It's just a simple model created to learn about L2E

I was under the impression that this was designed to make things strongly type - so why do I have to write "Role"? It seems that if I changed the name of the table, then this wouldn't create a compilation error...

My error is this:

The specified type member 'Roles' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.


The solution below allows me to now write the code:

proxy.User.Include(u => u.Role).First(u => u.UserId == userId)

Which is MUCH nicer!

+3  A: 
  1. Include is a hint to eager load, it does not force eager loading.
  2. Always check the IsLoaded property before referencing something that you hope was eager loaded by Include.
  3. There are ways to put a strongly typed object in the include statement, but there is no solution available to this issue out of the box with Entity Framework. Google something like: Entity Framework ObjectQueryExtension Include
Michael Maddox
I would be very interested in ways to get a strongly typed object in the include statement. The fact that it is untyped and results in a runtime error has given me headaches.
Jeroen Huinink
I just updated my answer with the phrase to Google for. Specifically "ObjectQueryExtension" is the magic you are looking for.
Michael Maddox
Thank you, the ObjectQueryExtension was perfect. Just dropped it in and it's now compile safe AND the error has gone
Paul
For those of you playing along at home - here's the Entity Framework ObjectQueryExtension I think Michael was talking about - http://msmvps.com/blogs/matthieu/archive/2008/06/06/entity-framework-include-with-func-next.aspx
Dan F
@Dan F: Rather than there being one right answer, I found several reasonable looking options when I first went looking. I didn't try to choose one because I think some of it is a matter of opinion and I didn't care to test them all. :)
Michael Maddox