在实体框架中将SQL转换为Linq查询
本文关键字:转换 Linq 查询 SQL 实体 框架 | 更新日期: 2023-09-27 18:26:53
如何在实体框架中将此查询转换为LINQ查询?我是一个仍在学校的新程序员
SELECT
studfirstname, studlastname, grade
FROM
students
INNER JOIN
Student_Schedules ON students.StudentID = Student_Schedules.StudentID
INNER JOIN
Classes ON Student_Schedules.ClassID = Classes.ClassID
INNER JOIN
Subjects ON Classes.SubjectID = Subjects.SubjectID
WHERE
SubjectName = 'Introduction to Art';
由于您是Lambda和LINQ的新手,我尝试在以下Lambda中尽可能具有描述性。。。。。也可以使用短格式的长别名student_tschedules为ss或studentsANDstudent_techules
s_sch。。。试试这个。。。希望这能有所帮助@阿卜杜勒·哈米德
var filteredData = context.Students // your starting point
.Join(context.Student_Schedules, // the source table of the inner join
students => students.StudentID, // Select the primary key (the first part of the "on" clause in an sql "join" statement)
student_schedules => student_schedules.StudentID),// the foreign key
(students, student_schedules) => new { students, student_schedules })
.Join(context.Classes,
classes => classes.ClassID,
studentsANDstudent_schedules => studentsANDstudent_schedules.student_schedules.ClassID),
(classes, studentsANDstudent_schedules) => new { classes, studentsANDstudent_schedules })
.Join(context.Subjects,
subjects => subjects.SubjectID,
studentsANDstudent_schedulesANDClasses => studentsANDstudent_schedulesANDClasses.classes.SubjectID),
(subjects, studentsANDstudent_schedulesANDClasses) => new { subjects, studentsANDstudent_schedulesANDClasses })
.Where(allMergedTables => allMergedTables.subjects.SubjectName == "Intoduction to Art").ToList();
这是上面一个的缩短版本。。。
var filteredData = context.Students
.Join(context.Student_Schedules, s => s.StudentID, sch => sch.StudentID),
(s, sch) => new { s, sch })
.Join(context.Classes, c => c.ClassID, s_sch => s_sch.sch.ClassID),
(c, s_sch) => new { c, s_sch })
.Join(context.Subjects, sj => sj.SubjectID, s_sch_c => s_sch_c.c.SubjectID),
(sj, s_sch_c) => new { sj, s_sch_c })
.Where(all => all.sj.SubjectName == "Intoduction to Art")
.ToList();
您可以使用LINQ语法:
from student in context.Students
join schedule in context.Student_Schedules on student.StudentID equals schedule.StudentID
join @class in context.Classes on schedule.ClassID equals @class.ClassID
join subject in context.Subjects on @class.SubjectID equals subject.SubjectID
where subject.SubjectName == "Introduction to Art"
var students = context.Students.Include("Student_Schedules")
.Include("Classes")
.Include("Subjects").Where(s => s.Subjects.Contains("Intoduction to Art"));
信息->https://msdn.microsoft.com/en-us/data/jj574232.aspx