【问题标题】:Get records via foreign key in another table in Entity Framework 6通过实体框架6中另一个表中的外键获取记录
【发布时间】:2016-05-13 11:00:45
【问题描述】:

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

我有这些课程:

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 to entity 语句,但没有成功。它似乎从座位表中归还了所有座位。

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

【问题讨论】:

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


    【解决方案1】:

    试试:

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

    【讨论】:

    • 谢谢你..我让它工作并把它变成了这个声明:return db.ReservationSeat.Where(rs =&gt; rs.ReservationId == reservationId).Select(rs =&gt; rs.Seat).ToList();
    • 老实说,我仍然没有得到“=>”。所以我最终一直使用很长的路
    【解决方案2】:

    您没有检查谓词中的 s 变量。您基本上是在向数据库询问“数据库中的任何 Reservation 行与 ID 匹配”的任何行。由于总有一个匹配,所有行在该谓词中都将评估为true

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

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

    【讨论】:

      【解决方案3】:

      在 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-26
        • 1970-01-01
        • 1970-01-01
        • 2019-10-15
        • 2015-01-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多