简体   繁体   English

具有LINQ,JOIN和ORDER BY且连接表中具有列的实体框架

[英]Entity Framework with LINQ, JOIN and ORDER BY with column in joined table

I'm working in VS 2015 with Entity Framework. 我正在使用实体框架在VS 2015中工作。 I got two tables called Formulas and Input_Field_Formulas. 我得到了两个表,分别称为Formulas和Input_Field_Formulas。 In one of my methods i wanna get an observablecollection of type Formulas to given search criterias. 在我的一种方法中,我想获得给定搜索条件的Formulas类型的可观察集合。 But the result list shall be in some sorted order. 但是结果列表应按某种排序的顺序。 Unfortunately the column for that sortorder is in the table Input_Field_Formulas. 不幸的是,该排序顺序的列在表Input_Field_Formulas中。

I tried to make it with LINQ but this doesn't work. 我试图用LINQ做到这一点,但这不起作用。 I wanted to get the formulas in descending order but i get them in the order as they were saved in the database. 我想按降序获取公式,但是我按保存在数据库中的顺序获取它们。

    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;
    }

How can i change the LINQ above or transform an SQL like the following to LINQ? 如何更改上面的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;

Thanks in advance! 提前致谢!

Try this way: 尝试这种方式:

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM