Richard Griffiths Richard Griffiths - 5 months ago 12
Vb.net Question

Linq to Sql navigation object instance properties are null or default

I'm using Linq to Sql and have a proper foreign key relationship setup in the underlying tables.

However, when I try to use navigation properties I have a subtle bug.

In the code sample below, when I put a watch on the PartDetails, I do get the fully populated parts. However, if I call the property on each part to check their values, the instance is now null.

I've hunted around for the last couple of hours to find an answer but so far coming up dry.

Can anyone clue me in as to why this is happening?

I'm on .net 4.6.1, Visual studio 2015 and Sql Server 2014.

I confess I couldn't find the correct place to fire off the DataLoadOptions but this seemed to work fine!

Partial Public Class LabourDetail
Private Sub OnCreated()
Dim db As New DataContext
Dim ds As DataLoadOptions = New DataLoadOptions()
ds.LoadWith(Function(c As LabourDetail) c.PartDetails)
db.LoadOptions = ds
End Sub
Public ReadOnly Property AnyPartsUnConsumed As Boolean
Get
'If I put a watch on the partdetails I do get a proper collection with proper instances.
Return PartDetails.Where(Function(p) p.PartsUnConsumed).Any
End Get
End Property
End Class

Partial Public Class PartDetail
'When we reach this point, the values in the instance are all Null / Default
Public Property PartsUnConsumed() As Boolean = _CheckPartsUnConsumed()
End Class


I'd be grateful for any assistance!

Answer

This Private Sub OnCreated() effectively doesn't do anything. It creates a context that immediately goes out of scope.

I assume there is some context that materializes LabourDetails from the database. That's the context to set the LoadOptions of.

Comments