通过Entity Framework 6中另一个表中的外键获取记录

时间:2016-05-13 11:00:45

标签: c# sql-server entity-framework linq entity-framework-6

我需要将所有座位都附加到特定预订中。

我有这些课程:

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; }
}

我试过这个linq到实体声明,但没有运气。它似乎从座位桌上归还了所有座位。

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();
    }
}

3 个答案:

答案 0 :(得分:5)

尝试:

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();
    }

答案 1 :(得分:0)

您没有检查谓词中的s变量。您基本上要求数据库中“数据库中的任何Reservation行与ID匹配”的任何行。由于总有一个匹配,因此所有行都将在该谓词中计算为true

听起来你正在寻找更像这样的东西:

.Where(s => s.Reservation.Id == reservationId)

答案 2 :(得分:0)

在EF Code-First中,ForeignKey可以应用于类的属性,而ForeignKey关系的默认Code-First约定要求外键属性名称与主键属性匹配。因此,您可以创建模型如下:

public class Seat
{
    public Guid Id { get; set; }

    public string RowNumber { get; set; }

    public int SeatNumber { get; set; }

    public virtual ICollection<Reservation> Reservations { get; set; }
}

public class Reservation
{
    public Guid Id { get; set; }

    public virtual ICollection<Seat> Seats { get; set; }
}

public static List<Seat> GetSeatsForReservation(Guid reservationId)
{
  List<Seat> result = null;
 using (var db = new EntityContext())
  {
     result = db.Seats.Where(
            s => s.Reservations.Id == reservationId).ToList();
    }
   return result ;
 }`

注意:1。这是多对多的关系,你可以将它改为1到多       2.导航属性必须声明为public,virtual