2017-04-20 23 views
0

我正在使用實體框架在VS 2015中工作。 我有兩個表稱爲公式和Input_Field_Formulas。 在我的一個方法中,我想獲得給定搜索標準的公式類型的observable集合。 但結果列表應按照某種排序順序。 不幸的是,該排序順序的列在Input_Field_Formulas表中。使用LINQ,JOIN和ORDER BY的實體框架與連接表中的列

我試圖讓它與LINQ,但這是行不通的。 我想按降序得到公式,但是我將它們按順序保存在數據庫中。

public ObservableCollection<Formulas> GetSelectedFormulas(int inputFieldId) 
    { 
     ObservableCollection<Formulas> formulasList = null; 

     try 
     { 
      using (paragraph16Entities db = new paragraph16Entities()) 
      { 
       formulasList = new ObservableCollection<Formulas>(db.Formulas.Join(db.Input_Field_Formulas 
        .Where(x => x.input_field_id == inputFieldId).OrderByDescending(x => x.sort_order), 
        a => a.formula_id, 
        b => b.formula_id, 
        (a, b) => new { Formulas = a, Input_Field_Formulas = b }) 
        .Select(a => a.Formulas) 
        .ToList()); 
      } 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
     } 

     return formulasList; 
    } 

如何更改上面的LINQ或將如下的SQL轉換爲LINQ?

SELECT Formulas.formula_id, Formulas.formula_name 
FROM Formulas 
JOIN Input_Field_Formulas ON Input_Field_Formulas.formula_id = Formulas.formula_id 
WHERE Input_Field_Formulas.input_field_id = 49 
ORDER BY Input_Field_Formulas.sort_order; 

在此先感謝!

回答

1

試試這個方法:

formulasList = new ObservableCollection<Formulas>(db.Formulas.Join(db.Input_Field_Formulas 
.Where(x => x.input_field_id == inputFieldId), 
a => a.formula_id, 
b => b.formula_id, 
(a, b) => new { Formulas = a, Input_Field_Formulas = b }) 
.OrderByDescending(x => x.Input_Field_Formulas.sort_order) 
.Select(a => a.Formulas) 
.ToList()); 
+0

非常感謝魯斯蘭!這樣可行。我在半小時前嘗試了類似的東西,但使用了首字母縮寫詞「b」而不是表格Input_Field_Formulas的新參考。 –