R.H
R.H

Reputation: 23

Entity Framework Returns NULL linked object C#

I use Entity Framework in my program, and I have a problem when a record is being removable from the table, the table linked objects come NULL.

Instead of doing

waitTravel = db.WaitTravels 
               .Where(w => w.suggestTravelId == suggestTravelId &&
                           w.wantedTravelId == wantedTravelId)
               .First();

if (waitTravel.WantedTravels.statusTravelId != 1)

I should do that:

 if (db.WantedTravels.Where(w => w.id == waitTravel.wantedTravelId).First().statusTravelId != 1)

Know something to help me?

Upvotes: 2

Views: 726

Answers (1)

Igor
Igor

Reputation: 62228

I believe what you are asking is why is waitTravel.WantedTravels null in your if statement. That is because you are missing an include statement and you do not have lazy loading enabled.

See the EF documentation on Loading Related Entities for additional options on how you can accomplish this. The easiest, and IMO best way, is to explicitly use Include when you know you want to retrieve a related property/collection.

waitTravel = db.WaitTravels 
               .Where(w => w.suggestTravelId == suggestTravelId &&
                           w.wantedTravelId == wantedTravelId)
               .Include(w => w.WantedTravels) // added
               .First();

If this is not what you are asking then please clarify your question.

Upvotes: 1

Related Questions