c# - 具有 LINQ、JOIN 和 ORDER BY 的 Entity Framework 以及连接表中的列

标签 c# mysql entity-framework linq

我正在 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/

相关文章:

mysql - LotusScript - 如何修复 LS :DO Error 720- ODBC could not complete the requested operation

c# - MVC 5 - 如何首先使用 EF 代码更新关系表

mysql - 我可以使用导航属性加载一个包含表的整个数据库吗?

mysql - 排序规则与嵌套选择的非法混合

c# - 是否始终保证 LINQ 查询的结果顺序正确?

c# - 获取两个列表之间的差异

c# - 上传的文件未保存到文件系统

mysql - 无法从tomcat连接到MySQL数据库

c# - Linq 查询中的“IN”和 'NOT IN'

c# - 将字符串 decimal 转换为 int