Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

code first auto gen proxy class navigation and collection properties are null

For all of my POCOs, the navigation and collection properties are all null.

Let me provide some background. I have a complex code first project using EF 4.3.1. Proxy generation was disabled. Collection and navigation properties were managed manually.

I'm now enabling proxy creation and lazy loading. When debugging, I can see that my entity (which is cast to my known POCO type) is now actually an auto generated proxy class. So far so good.

Now, when I look at my navigation properties, they are null. Similarly, my collection properties are null.

Using reflection, I can see that the proxy class HAS overridden my navigation and collection properties.

All navigation and collection properties are virtual. e.g:

public virtual NavigationType NavigationName { get; set; }
public virtual ICollection<CollectionType> CollectionName { get; set; }

Also, all tables are initialised as such:

modelBuilder.Entity<TEntity>()
.Map(m =>
{
    m.MapInheritedProperties();
    m.ToTable("TableName");
});

I can also confirm that the database is generated as expected. Foreign keys are all present and are associated with the expected fields.

Why are they null? How can I diagnose this further?

like image 285
Paul Fleming Avatar asked Apr 22 '13 15:04

Paul Fleming


1 Answers

How can I diagnose this further?

You could check for example if the entities you are inspecting are attached to the context by looking into the change tracker's context.ChangeTracker.Entries() collection.

It's well possible that you have a dynamic proxy with all navigation properties being null, for example:

Entity entity = context.Entities.Create();

entity will be a proxy, but NavigationName and CollectionName will be null and they will stay null even when you access these properties (leading to NullReferenceExceptions). This will only change when you attach the entity:

context.Entities.Attach(entity);

If you access the properties now lazy loading should run. NavigationName can stay null if there is no related entity in the database, but the collection CollectionName should never be null after attaching and accessing it. If there are no related entities in the DB the result should be an empty collection, but not null.

like image 199
Slauma Avatar answered Nov 01 '22 13:11

Slauma