【问题标题】:Where to execute extra logic for linq to entities query?在哪里执行 linq to entity 查询的额外逻辑?
【发布时间】:2010-03-15 21:50:00
【问题描述】:

假设我想填充基于客户实体框架模型构建的 CustomerViewModel 列表,其中一些字段(如余额)单独计算。

下面我有适用于列表的代码 - 它在我的服务层中实现,但我也想在我从数据库中获取一个项目并在我正在访问的不同服务中执行时执行此代码客户数据也是如此。

我应该如何做到这一点以确保性能但不重复代码 - 用于计算余额的代码?

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();
}

【问题讨论】:

    标签: c# .net asp.net-mvc entity-framework


    【解决方案1】:

    在你的业务(服务)层试试这个:

    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() 必须返回 IQueryable。

    【讨论】:

      猜你喜欢
      • 2012-08-05
      • 1970-01-01
      • 2011-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多