Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get records via foreign key in another table in Entity Framework 6

I need to get all seats attached to a specific reservation.

I have these classes:

public class Seat
{
    public Guid Id { get; set; }
    public string RowNumber { get; set; }
    public int SeatNumber { get; set; }
}

public class ReservationSeat
{
    public Guid Id { get; set; }
    public Guid ReservationId { get; set; }
    public Guid SeatId { get; set; }

    public Reservation Reservation { get; set; }
    public Seat Seat { get; set; }
}

I have tried with this linq to entities statement but with no luck. It seems to return all the seats from the seats table.

public static List<Seat> GetSeatsForReservation(Guid reservationId)
{
    using (var db = new EntityContext())
    {
        return db.Seats.Where(s => db.ReservationSeat
                                     .Select(rs => rs.ReservationId)
                                     .Contains(reservationId)).ToList();
    }
}
like image 458
Michael Kirkegaard Avatar asked May 13 '16 11:05

Michael Kirkegaard


People also ask

How can I get data from another table using foreign key?

To retrieve data from both table associated with foreign key i.e(common column) you have to join both the tables. if you matching data from both table then use INNER JOIN. >

How do I use lazy loading in entity Framework?

Lazy loading means delaying the loading of related data, until you specifically request for it. When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook.

What is inverse property in entity Framework?

The InverseProperty attribute is used to denote the inverse navigation property of a relationship when the same type takes part in multiple relationships.


1 Answers

Try:

public static List<Seat> GetSeatsForReservation(Guid reservationId)
    {
        var db= new  EntityContext();
        return (from s in db.ReservationSeat
                where s.ReservationID==Guid
                select s.seat).ToList();
    }
like image 182
Aimnox Avatar answered Nov 10 '22 00:11

Aimnox