Question

For part of the project I'm currently working on, I have a set of four tables for syndicatable actions. One table is the abstract base for the other three, and each table is represented in my EF model like so:

EF Model -- Actions http://chris.charabaruk.com/system/files/images/EF+Model+Actions.png

There are two problems that I'm currently facing with this, however. The first problem is that Actor (a reference to a User) and Subject (a reference to an entity of the class associated with each type of action) are null in my subclasses, despite the associated database columns holding valid keys to rows in their associated tables. While I can get the keys via ActorReference and SubjectReference this of course requires setting up a new EF context and querying it for the referenced objects (as FooReference.Value is also null).

The second problem is that the reciprocal end of the relationship between the concrete action classes and their related entity classes always turn up nothing. For example, Task.RelatedActions, which should give me all TaskAction objects where Subject refers to the particular task object on which RelatedActions is called, is entirely devoid of objects. Again, valid rows exist in the database, Entity Framework just isn't putting them in objects and handing them to me.

Anyone know what it is I'm doing wrong, and what I should do to make it work?

Update: Seems that none of the relationship properties are working in my entity model any more, at all. WTF...

Was it helpful?

Solution

I think the issue you are experiencing here is that by default the EF does not automatically load related entities. If you load an entity, the collection or reference to related entities will be empty unless you do one of the following things:

1) Use eager loading in order to retrieve your main entity and your related entity in a single query. To do this, modify your query by adding a call to the Include method. In your sample above, you might use the following query:

from a in context.Actions.Include("Actor") select a

This would retrieve each of the actions with the related Actor method.

2) Use explicit lazy loading to retrieve the related entity when you need it:

action1.ActorReference.Load()

In the version of the EF which will ship with .Net 4.0, you will also have the following additional option:

3) Turn on implicit lazy loading so that related entities will automatically be retrieved when you reference the navigation property.

  • Danny
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top