views:

1495

answers:

2

When I have tables in my database that have PK/FK relationships (int) and when they are modeled by the Entity Framework designer everything seems as it should be. I can write the code below and everything seems like it's going to work fine as well but then when I run the code I get an error on the project.Status.StatusName saying the Object reference not set to an instance of an object. I guess I was under the impression that the framework populated the associated entities when you populate the parent entity.

    Dim db As New MyDbModel.MyDbEntities()

    Dim project As MyDbModel.Project = (From p In db.Project Where p.ProjectID = 1).First

    Response.Write(project.ProjectName)        
    Response.Write(project.Status.StatusName)
+4  A: 

Try using Include(RelationshipName)

Dim db As New MyDbModel.MyDbEntities()    
Dim project As MyDbModel.Project = (From p In db.Project.Include("Status") Where p.ProjectID = 1).First    
Response.Write(project.ProjectName)            
Response.Write(project.Status.StatusName)
bendewey
I have a follow up question that I've posted here: http://stackoverflow.com/questions/384138/entity-framework-how-do-i-use-the-entity-relationships-in-my-extended-classes
EdenMachine
+3  A: 

Entity Framework does not load related entities unless you tell it to. In order to access related entities you need to either Load() them explicitly or use Include(). Here's a short sample.

http://blogs.msdn.com/bethmassi/archive/2008/12/10/master-details-with-entity-framework-explicit-load.aspx

Kim Major