1

I have the following tables in my database:

- Reservation
- TrainStation
- Train
- Traveller
- Reservation_Traveller
- TrainSeats: Attributes are: Train_Id, Seat, Traveller_Id

I want to find the TrainSeats rows of a particular Reservation

I have a Reservation object that contains an ICollection<Traveller> property containing the travellers of which I want to remove their seats from the TrainSeats table. I fetched the reservation object from the database like this:

var reservation = db.Reservation.Where(r => r.Id == id).FirstOrDefault();

So I want to do something like this:

db.TrainSeats.Where(ts => ts.Traveller_Id IN reservation.Travellers)

1 Answer 1

1

First select the travelers id:

var ids=reservation.Travellers.Select(e=>e.Id);

Then use Contains extension method which is translated into IN in sql:

var query=db.TrainSeats.Where(ts => ids.Contains(ts.Traveller_Id));

I guess if you use the FK property and navigation properties you can do it in one query:

var query= db.Travellers.Where(e=>e.ReservationId==id).SelectMany(t=>t.TrainSeats);
Sign up to request clarification or add additional context in comments.

3 Comments

This is causing a NotSupportedException, the message is: {"Unable to create a constant value of type 'Traveller'. Only primitive types or enumeration types are supported in this context."}
Did you select the ids? you need to select an scalar property to use Contains as I show in my answer, in your case it would be traveler ids. That error is because you are using Contains comparing with entities instead of scalar value
I got it working, it was another condition that caused the exception. Thanks.

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.