Reputation: 1579
I have 3 table connected with primary and foreign concept.
model -> studentRecord
public class studentRecord
{
public string studentName{ get; set; }
public int year{ get; set; }
}
Table 1 -> student
studentId studentName
----------------------
1 Sam
2 Mani
3 rajah
Table 2 -> subject
subjectid subjectName
------------------------
1 english
2 maths
3 physics
table 3 -> register
registerId studentId subjectid Year
--------------------------------------------
1 1 1 1
2 1 2 1
3 1 3 1
4 1 1 2
5 1 2 2
6 1 3 2
i want to get the record of the second year of the student.
my linq code
var op = (from student in db.student.where(x => x.studentId == 1)
join register in db.register
on student.studentId equals register.studentId
select new studentRecord{studentName = student.studentName, year = register.Year}).ToList<studentRecord>().Max(x => x.Year)
I am getting error. Is there any appoach with good performance. Thanks in advance
Upvotes: 1
Views: 137
Reputation: 14053
Have tested the query in Linqpad and the following query works just fine for me.
void Main()
{
var op = (from student in Students.Where(x => x.StudentId == 1)
join register in Registers
on student.StudentId equals register.StudentId
select new {student = student.StudentName, Year = register.Year})
.Max(x => x.Year);
op.Dump();
}
And profiler shows the following SQL.
exec sp_executesql N'SELECT MAX([t1].[Year]) AS [value]
FROM [student] AS [t0]
INNER JOIN [register] AS [t1] ON [t0].[studentId] = [t1].[studentId]
WHERE [t0].[studentId] = @p0',N'@p0 int',@p0=1
Anyway what you probably want is this:
from student in Students.Where(s => s.StudentId == 1)
join register in Registers.Where(r => r.Year == Registers.Max(x => x.Year))
on student.StudentId equals register.StudentId
select new studentRecord
{
studentName = student.StudentName,
year = register.Year
})
.ToList<studentRecord>();
Students
is in your code db.student
etc.
Upvotes: 1