简体   繁体   中英

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 =
        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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM