2

I have a problem with sum of navigation properties using entity framework

Here is my example classes

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ObservableCollection<Call> Calls { get; set; }
    [NotMapped]
    public decimal TotalCallDuration { get { return Calls.Sum(c => c.Value); } }

}

public class Call
{
    public int Id { get; set; }
    public int CustomerID { get; set; }
    public virtual Customer Customer { get; set; }
    public decimal Value { get; set; }
    public DateTime Date { get; set; }
}

This works well but when i have hundreds of records it is very slow

How can i make this faster but without losing functionality?

Thanks

Ruben Alves
  • 41
  • 1
  • 3

1 Answers1

2

what you want to do is: customer.TotalCallDuration = context.Call.Sum(x => x.Value).Where(x => x.CustomerID == customer.Id);

SOfanatic
  • 5,523
  • 5
  • 36
  • 57
  • Is there any other way to do this witout having to go to the server again? – Ruben Alves Apr 19 '13 at 12:19
  • you can eagerly load your `Calls` into your `Customer` : `context.Customers.Include(c => c.Calls).Where(c => c.Id == Id).ToList();` where `Id` is the `Id` of the customer you want. – SOfanatic Apr 19 '13 at 13:38
  • This will not work in queries, you can use TotalCallDuration with your example in Linq to SQL. – Tomas Nov 13 '17 at 11:35