Entity Framework: Many to One property and how to load

Ok so this is the situation, you’ve just stolen 50 billion dollars from various wealthy people using a ponzi scheme and you’ve been caught. What do you do? I have no idea but if that’s your situation and you’ve ended up at this site, I’m guessing your escape route has something to do with the Entity Framework and how to load a many to one relationship. Or maybe you’re just interested in the latter anyhow.

So here’s the problem I ran into the other day. I have a Site table and a Role table, and every Role record has a SiteID (Foreign Key) that the Entity Map represents in a property. (Site Class) Now, when I “hydrate” a Role, the Site property is null. This is because Entity Framework, in a round about way, supports lazy loading sort of. (Lazy Loading meaning that any relationship, be it a Site object on a Role or say a Users list on a Role, will not be loaded at the time you “hydrate” the main object and will only be loaded when the property is accessed.) So it makes sense that the Site object exposed by the property is not loaded yet because I haven’t accessed the property.

With the Entity Framework, and one to many relationships (Say a Users list on a Role object) you have to not only access the property, but you have use the Load method to make sure it gets loaded:

    from user in someRole.Users.Load()

Well with a many to one relationship (Many Roles to one Site) this is a propblem since the Site property returns only a single Site:

    someRole.Site.Load(); //Boom, not possible

Load can’t be used since Site isn’t a collection. So how the hell do I load this stupid thing? Well that has to be done in the query itself. Kind of annoying:

    context.Role.Include("Site").Where(someClause).ToList();

As you can see, in that query I had to add the Include method and the value is actually the property name. Now when I look at the list of roles returned, the roles now have the Site property loaded. As I said, kind of annoying, but there is something interesting about these relationships that I’ll post about next.

4 thoughts on “Entity Framework: Many to One property and how to load”

Comments are closed.