我正在 VS 2015 中使用 Entity Framework 。 我有两个表,分别称为 Formulas 和 Input_Field_Formulas。 在我的方法之一中,我想获得给定搜索条件的类型公式的可观察集合。 但结果列表应按某种排序顺序。 不幸的是,该排序顺序的列位于表 Input_Field_Formulas 中。
我尝试使用 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;
提前致谢!
最佳答案
试试这个方法:
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());
关于c# - 具有 LINQ、JOIN 和 ORDER BY 的 Entity Framework 以及连接表中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43514778/