E
E
Eugene2017-02-26 01:58:42
.NET
Eugene, 2017-02-26 01:58:42

How to correctly form a query for Entity Framework for two tables?

Hello!
There are two tables - students and debt:

CREATE TABLE "Student" (
  `ID`	INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
  `Last_name`	TEXT NOT NULL,
  `First_name`	TEXT NOT NULL,
  `Patronymic`	TEXT,
  `Gender`	INTEGER NOT NULL,
  `id_group`	INTEGER NOT NULL,
  FOREIGN KEY(`id_group`) REFERENCES `Group`(`ID`) ON DELETE CASCADE
);
CREATE TABLE "Debts" (
  `ID`	INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
  `id_student`	INTEGER NOT NULL,
  `Date_last_payment`	DateTime NOT NULL,
  `Last_payment`	INTEGER NOT NULL,
  `Debt`	INTEGER NOT NULL,
  FOREIGN KEY(`id_student`) REFERENCES `Student`(`ID`) ON DELETE CASCADE
);

Database in SQLite. An Entity Framework model (version 6) has been formed for it.
How to correctly compose an EF query to select all debtors (that is, those who, for the last payment in the "Debts" table, have a debt in the `Debt` field)? So that APPLY JOIN is not used (SQLite does not support it).
The SQL query for this selection turned out to be the following (I did not list all the columns in the SELECT):
SELECT Student.ID, Student.Last_name, MAX(Debts.Date_last_payment), Debts.Debt 
FROM Student 
JOIN Debts ON Student.ID=Debts.id_student 
WHERE Debts.Debt <> 0 
GROUP BY Student.ID;

Thank you!
UPD Tried with the following query:
var query = _universityDB.Student
.Join(_universityDB.Debts, s => s.ID, d => d.id_student, (s, d) => new
{
    Student = s,
    Debts = d
})
.GroupBy(s => s.Student.ID)
.Select(s => new
{
    Student = s.OrderByDescending(r => r.Debts.Date_last_payment).FirstOrDefault()
})
.Where(s => s.Student.Debts.Debt != 0);

But then APPLY JOIN is used.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2017-02-26
@k1lex

LINQ to Entities?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question