Relationship fixup runs when an entity gets attached to a context - either manually by calling Attach
or when the entity is materialized as a result of a query (your case).
It is based on foreign keys of an entity and works in both directions:
If the context already contains an entity
A
with a foreign keyf
to entityB
and an entityB
is being attached to the context that has a primary key with the same valuef
as the foreign key inA
(i.e. the two entities are related by an FK relationship) then Entity Framework will do the following:- If
A
has a navigation reference property toB
it will assign the attached entityB
to this property. - If
B
has a navigation reference property toA
(one-to-one relationship) it will assignA
to this property. - If
B
has a navigation collection property toA
(one-to-many relationship) it will addA
to this collection in the attached entityB
. If the collection isnull
it will instantiate the collection before adding.
- If
If an entity
B
is being attached to the context that has a foreign keyf
to an entityA
that the context already contains and that hasf
as primary key EF will set the navigation properties based on the same rules like above.
As a side note: The fact that relationship fixup is based on foreign keys (they are always loaded when you query an entity, no matter if the FK is exposed as property in the model class or not) is also the reason why relationship fixup does not apply to and does not work for many-to-many relationships because the two entities of a many-to-many relationship don't have a foreign key.
Now, if there are no related StudentModules
in your case there is no StudentModule
entity that gets loaded into the context and there is nothing what EF could target for a fixup. Keep in mind that the fixup algorithm is not related to a particular query and does not only fix relationships between entities that this query would materialize but it will consider all entities for fixup that the context already contains, no matter how they came into the context. If you would want that collections get instantiated as empty collections EF had run through all attached parent entities of StudentModules
and just create an empty collection. It makes no sense to do this during fixup instead of creating empty collections up-front before entities get attached to a context.
I can put a constructor in the poco to initialize the list, which fixes it, but the this collection is a virtual member in the poco (based on an EF video!) - surely this is not the way to go?
In my opinion it is the best solution if you don't want to have null
collections in your model class instances. It doesn't matter if the collection is declared as virtual
(to enable lazy loading) or not. A collection type does not have a derived proxy type, only the instances that get added to the collection are derived proxies. In both case you can just use StudentModules = new HashSet<StudentModule>();
(or List
if you prefer).