Dan
Dan

Reputation: 71

Populating dropdown lists based on EF child relationships

I'm writing a simple app using EF for the first time. (EF6)

My database has a few tables and they have foreign key relationships between the tables. The app will have simple display, add, update, delete functions for each table.

Entity classes are built with the many to one relationships.

Table 'cars' CarID OwnerID ColorID Make Model

Table 'Owners' OwnerID Fname Lname

Table 'Colors' ColorID ColorName

On the Cars 'management' page - The Owners and color tables should be represented as dropdownlists.

Note - This is a webforms app.

I'm calling my 'GetCar' function from the behind code and passing the CarID.

Here is my function, it works, however I cant access the Owner properties.

Public Shared Function getCarByID(CarID As Integer) As Car
        Using db As MyAppContext = New MyAppContext
            Dim car As New Car
            car = db.Cars.First(Function(x) x.CarID = CarID)
            Return car
        End Using
End Function

So my questions are: 1: How do I populate the 'Owner' dropdown list, I assume i need to write a separate function to return a List of Owners object, correct?

2: How do I access the properties of the Owner associated with a Car?

One of my attempts to do so (from aspx behind code):

Dim car As Car = New Car
    car = Car.getCarByID(CarID)
    Me.lblOwnerFirstName.Text = car.Owner.Fname

Intellisense displays the owner properties when typing car.owner.

I can retrieve all 'car' properties without issue.

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

I also tried moving the using block into the code behind for testing and setting Me.lblOwnerFirstName.Text = car.Owner.Fname there, but same error.

Any comments or help appreciated, Thanks,

Upvotes: 1

Views: 102

Answers (1)

Kiran Varsani
Kiran Varsani

Reputation: 587

Usually Entity framework uses Lazy loading approach to load data. This means it only loads data which are asked in your query. In your case, Entity framework has returned Car object and then disposed your context object at the end of using statement. So if you try to access owner from your car it throws error. To solve this, you need to tell Entity Framework to include Owner with Car like this.

Public Shared Function getCarByID(CarID As Integer) As Car
        Using db As MyAppContext = New MyAppContext
            Dim car As New Car
            car = db.Cars.Include("Owner").First(Function(x) x.CarID = CarID)
            Return car
        End Using
End Function

This will also return Owner along with Car object.

Upvotes: 1

Related Questions