![](/img/trans.png)
[英]Get foreign key records using Entity Framework and display in Angular
[英]Get records via foreign key in another table in 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();
}
}
嘗試:
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();
}
您沒有檢查謂詞中的s
變量。 您基本上要求數據庫中“數據庫中的任何Reservation
行與ID匹配”的任何行。 由於總有一個匹配,所有行將在該謂詞中評估為true
。
聽起來你正在尋找更像這樣的東西:
.Where(s => s.Reservation.Id == reservationId)
在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 2.導航屬性必須聲明為public,virtual
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.