2017-04-25 153 views
0

我有2個表'Car'和'Booking'。車表包含屬性CarID(PK),品牌,型號和尺寸。 「預訂」表包含ID(PK),CarID(FK),StartDate和EndDate。用SQL查詢LINQ查詢

的2個表包含我已經把自己的一些數據:

預訂 - enter image description here 汽車 - enter image description here

這是我的查詢到目前爲止:

var searchQuery = from c in db.Cars 
    from b in db.Bookings 
    where c.Size == comboBox_CarType.Text 
    && RentEndDate.SelectedDate < b.EndDate && RentStartDate.SelectedDate > 
    b.StartDate 
    select c.CarID + " - " + c.Make.Trim() + " - " + c.Model.Trim(); 

用戶輸入3信息片段:大小,開始日期和結束日期爲他們想租的汽車。然後,這將從汽車數據庫中提供當時可用的汽車。

我的問題:我已經完成了大小比較然而,當我嘗試在現有的汽車上面的查詢不會在車輛帶來加載,即使邏輯對我來說很有意義

+1

*首先不要使用Join *。 ORM的工作是將表映射到類和*關係*。如果你正確配置你的上下文,並添加一個'Car'屬性來預訂,你不需要任何連接。只需加載預訂,所有的汽車都會隨它們一起提供。 –

+1

使用ORM進行工作時,發佈*表*不起作用。你的*類*和你的*上下文配置*在哪裏? –

回答

1

你錯過了內部聯接部分,您的查詢應該是

var searchQuery = from c in db.Cars 
    join b in db.Bookings on c.CarId= b.CarId 
    where c.Size == comboBox_CarType.Text 
    && RentEndDate.SelectedDate < b.EndDate && RentStartDate.SelectedDate > 
    b.StartDate 
    select c.CarID + " - " + c.Make.Trim() + " - " + c.Model.Trim(); 
1
var searchQuery = 
    from b in db.Bookings 
    where b.Car.Size == comboBox_CarType.Text 
    && RentEndDate.SelectedDate < b.EndDate && RentStartDate.SelectedDate > 
    b.StartDate 
    select b.Car.CarID + " - " + b.Car.Make.Trim() + " - " + b.Car.Model.Trim(); 

booking應該有一個car屬性,如果它不工作,那麼你必須做出booking和之間的使用carId

var searchQuery = from c in db.Cars 
    join b in db.Bookings on c.CarID equals b.CarID 
    where c.Size == comboBox_CarType.Text 
    && RentEndDate.SelectedDate < b.EndDate && RentStartDate.SelectedDate > 
    b.StartDate 
    select c.CarID + " - " + c.Make.Trim() + " - " + c.Model.Trim(); 
0

@Alejandro對它。你可以使用你使用過的語法,但你必須在某種id上加入這兩個表。

我也覺得你會希望開始日期和結束日期也是=。如果汽車準備好了,你想租用它?

var searchQuery = 
     from c in db.Cars 
     from b in db.Bookings 
     where c.Size == comboBox_CarType.Text 
      && RentEndDate.SelectedDate <= b.EndDate 
      && RentStartDate.SelectedDate >= b.StartDate 
      && c.CarId = b.CarId 
     select c.CarID + " - " + c.Make.Trim() + " - " + c.Model.Trim(); 
0

你也可以這樣做。

var eligibleBookings = cars.Where(r => bookings 
      .Where(b => (b.StartDate <= start) && (b.EndDate <= end)&& cars 
      .Where(c => c.Size == comboBox_CarType.Text) 
      .Select(c => c.CarId).Distinct().ToList() 
      .Contains(b.CarId)) 
      .Select(c => c.CarId).Contains(r.CarId));