Saleh Bagheri Saleh Bagheri - 1 month ago 5
C# Question

How To Sum Tuition of Each Student: What Query?

I am developing a ASP.NET MVC 5 Application with EF6. I have about 5000 entities and I'm querying them through LINQ to collect all students with total tuitions:


public class Student
public string ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual IList<Payment> Payments { get; set; }

public class Payment
public string ID { get; set; }
public double Tuition { get; set; }
public int Month { get; set; } //Tuition added monthly
public Student Student { get; set; }

for example:

student 1:
{payments{1000}, payments{1500}, payments{3000}}
student 2:
{payments{400}, payments{1700}, payments{4000}}
student n:
{payments{5000}, payments{6500}, payments{7000}}

and query i want is collection of student with total tuition of each student:

var result = {{student1, 5500}, {student2, 6100}, ...}

What's the best way to achieve this?


You can use this LINQ query and let EF construct the query a SQL server do the work.

context.DbSet<Student>().Select(o => new { 
    Student = o, 
    TotalTution = o.Payments.Sum(p => p. Tution)