Stono
Stono

Reputation: 2337

Entity Framework 5, Code First Lazy Loading Not Working

I am trying to get my head around EF, and have hit a hurdle, i'm using the simple blog/post structure and have created the classes, for example:

''' <summary>
''' Represents a blog in the database
''' </summary>
''' <remarks></remarks>
Public Class Blog
    Public Property BlogID As Integer
    Public Property Name As String

    ''' <summary>
    ''' All posts in this blog
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property BlogPosts As List(Of BlogPost)
End Class

Now if I do this

    Using db As New DBContext
        _blog = db.Blogs.
            FirstOrDefault(Function(m) m.BlogID = BlogID)

        Dim _posts = _blog.BlogPosts.First
    End Using

I get a null reference exception on BlogPosts, it isn't lazy loading.

Now I can force it to work using .Include, but that defeats the object.

All the c# examples I find declare there BlogPosts property with "Virtual", I don't know what the VB version of that would be? For example:

public virtual ICollection<BlogPosts> BlogPosts { get; set; } 

Upvotes: 0

Views: 900

Answers (2)

Corey Adler
Corey Adler

Reputation: 16149

Use the overrides keyword, as shown in this example.

That should do the trick.

Upvotes: 0

Stono
Stono

Reputation: 2337

Making the property Overridable sorted it

Upvotes: 1

Related Questions