Answer the question
In order to leave comments, you need to log in
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
);
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;
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);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question