简体   繁体   中英

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

I'm working in VS 2015 with Entity Framework. I got two tables called Formulas and Input_Field_Formulas. In one of my methods i wanna get an observablecollection of type Formulas to given search criterias. But the result list shall be in some sorted order. Unfortunately the column for that sortorder is in the table Input_Field_Formulas.

I tried to make it with LINQ but this doesn't work. 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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