Entity Framework: Lazyloading appears to be off despite explicitly turning it on?

63 Views Asked by At

It would appear that my model first EF set up is not lazy loading related table records despite explicitly turning it on (which I understand I should not have to do since it's model first).

Code follows:

Using db As New Entity()

    db.Configuration.LazyLoadingEnabled = True

    Dim objectList as List(Of tableName) = _
        db.tableName.Include("relatedTableName") _
        .Where(Function(x) x.col1 = someValue) _
        .OrderBy(Function(x) x.col2).ThenBy(Function(x) x.col3).ToList()

    int testVal = 0

    For Each item As tableName In objectList
        testValue = item.relatedTableName.idColumn
    Next
End Using

I get a System.NullReferenceException: Object reference not set to an instance of an object. error on this line:

testValue = item.relatedTableName.idColumn

In fact, item.relatedTableName doesn't have a value either. I have verified that I should be getting records back by writing an inner join statement in SQL.

What's going on here?

1

There are 1 best solutions below

0
On BEST ANSWER

Apparently, the navigation property from a nullable field to the related table when there is more than 1 foreign key between the two tables will do this if you use the wrong navigation property.

That is to say that navigation properties relatedTableName and relatedtableName1 need to be used according to the data you want. If the first one points to a nullable street address column and the second one points to a non-nullable zip code column, point to the right one and expect a possible null object and null column.