2

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?

2
  • Do you mean why is waitTravel.WantedTravels null in your if condition? Commented Jun 13, 2016 at 13:37
  • yes, thanks for you Commented Jun 13, 2016 at 14:09

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

There is a way to do this in a general way the entire program?
@R.H - You can enable lazy loading for the entire DbContext. See How to: Use Lazy Loading to Load Related Objects

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.