Let say that I want to populate a list of CustomerViewModel which are built based on Customer Entity Framework model with some fields (like Balance) calculated separately. Below I have code which works for lists - it is implemented in my service layer, but also I want to execute this code when I just get one item from the database and execute is as well in different services where I'm accessing Customers data as well. How should I do this to ensure performance but to to not duplicate code - the one for calculating Balance?
public List<CustomerViewModel> GetCustomerViewModelList()
{
IQueryable<CustomerViewModel> list = from k in _customerRepository.List()
select new CustomerViewModel
{
Id = k.Id,
Name = k.Name,
Balance =
k.Event.Where(z => z.EventType == (int) EventTypes.Income).Sum(z => z.Amount)
};
return list.ToList();
}