0

I'm using .NET 3.5 and I'm having trouble loading the Entity References automatically. Ideally, and it seems to work sometimes, I would like something like

Dim relocations = ctx.EmployeeRelocations.Where(Function(o) o.Employee.EmployeeNumber = employeeNumber).ToList()
If Not relocations.Where(Function(o) o.ValidTerritory.Territory = territory).Any() Then

where ValidTerritory is a reference type in relocations. But instead, when I try that, I get Object Not set to an instance... for o.ValidTerritory. So, I can do this and everything works fine:

If Not relocations.Where(Function(o)
                             o.ValidTerritoryReference.Load()
                             Return o.ValidTerritory.Territory = territory
                         End Function).Any() Then

In theory, it makes sense what's happening, but I don't understand why I need the explicit Load and why this behavior seems to come and go (that is, it sometimes loads the references fine with no explicit load).

1 Answer 1

1

Try using Include to get that data:

relocations.Include("ValidTerritory").Where(Function(o) o.ValidTerritory.Territory = territory).Any()
Sign up to request clarification or add additional context in comments.

4 Comments

I got 'Include' is not a member of 'System.Collections.Generic.List(Of ...EmployeeRelocation)' where relocations is defined Dim relocations = ctx.EmployeeRelocations.Where(Function(o) o.Employee.EmployeeNumber = employeeNumber).ToList() Also note that digging into the Employee reference here works just fine...
.Include has to be made directly on context.Table element, so in your example it would be ctx.EmployeeRelocations.Include("ValidTerritory").
That got rid of the error, but caused further issues with my queries. It also made the statement more complex than it seems it should have to be since that type of referencing is working in other places. I don't think I can mark this as accepted because the underlying issue is still there, but +1 for the help.
I just went back and revisited this when I got some time and also found this question which basically said the same thing and that this was essentially by design. I learned a good bit about EF that I didn't know when I started the project this was a part of. And you were spot on with your answer; I'm not sure why I had trouble with it the first time through.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.