Where to execute extra logic for linq to entities query?
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 =开发者_StackOverflow社区
k.Event.Where(z => z.EventType == (int) EventTypes.Income).Sum(z => z.Amount)
};
return list.ToList();
}
Try this in you business (service) layer:
private List<CustomerViewModel> GetCustomerViewModelList(IQueryable<Customer> customerList)
{
vaar list = from k in customerList
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();
}
public List<CustomerViewModel> GetCustomerViewModelListForAllCustomers
{
return GetCustomerViewModelList(_repository.List());
}
public CustomerViewModel GetCustomerViewModelListForOneCustomers(int id)
{
return GetCustomerViewModelList(_repository.List().Where(c => c.Id == id)).First();
}
_repository.List()
must return IQueryable.
精彩评论