1

我需要限制从数据库返回的客户 bo 的数量,因为我正在搜索部分客户名称,而目前在搜索“a”时我得到了 600 多个 bo。我想将其限制为 20。我目前的代码是

    public IEnumerable<Customer> FindCustomers(string partialCustomerName)
    {
        if (string.IsNullOrEmpty(partialCustomerName)) 
          throw new ArgumentException("partialCustomerName must be at least one character long");
        var criteria = Criteria.Create<Customer, string>(cust =>   cust.CustomerName, Criteria.ComparisonOp.Like, partialCustomerName + "%");
        return Broker.GetBusinessObjectCollection<Customer>(criteria);
    }
4

3 回答 3

2

我现在无法对此进行测试,但您应该可以使用 LoadWithLimit() 方法进行测试。totalRecords 变量将保存找到的总结果数,以防您想要包含一些信息,例如“显示 20 个 totalRecords 结果。”。

public IEnumerable<Customer> FindCustomers(string partialCustomerName)
{
    if (string.IsNullOrEmpty(partialCustomerName)) 
      throw new ArgumentException("partialCustomerName must be at least one character long");

    var criteria = Criteria.Create<Customer, string>(cust =>   cust.CustomerName, Criteria.ComparisonOp.Like, partialCustomerName + "%");
    int totalRecords;
    return Broker.GetBusinessObjectCollection<Customer>().LoadWithLimit(criteria, 0, 20, ref totalRecords);
}
于 2011-06-02T13:18:56.957 回答
1

Till 在正确的轨道上,但没有给出正确的语法。代理用于从当前数据访问器加载集合,而不是用于创建新的。所以代码将是:

public IEnumerable<Customer> FindCustomers(string partialCustomerName)
{
    if (string.IsNullOrEmpty(partialCustomerName)) 
      throw new ArgumentException("partialCustomerName must be at least one character long");

    var criteria = Criteria.Create<Customer, string>(cust =>   cust.CustomerName, Criteria.ComparisonOp.Like, partialCustomerName + "%");
    int totalRecords;
    var col = new BusinessObjectCollection<Customer>();
    col.LoadWithLimit(criteria, "CustomerName", 0, 20, ref totalRecords);
    return col;
}

应该这样做!请将答案授予蒂尔,而不是我。他做的研究最多。我刚刚更正了语法:)

编辑:在下面对丑陋的 API 发表评论后,我将包括对方法的建议更改以使其看起来更干净(感谢您的建议 @GloryDe​​v):

public IEnumerable<Customer> FindCustomers(string partialCustomerName)
{
    if (string.IsNullOrEmpty(partialCustomerName)) 
      throw new ArgumentException("partialCustomerName must be at least one character long");
    var col = new BusinessObjectCollection<Customer>();
    col.LoadWithLimit("CustomerName Like " + partialCustomerName + "%", "CustomerName", 20);
    return col;
}

第二个参数是排序依据的字段,这对于具有限制的提取有意义。希望这可以帮助。

于 2011-06-02T14:36:45.717 回答
1

安德鲁 你总是可以这样做看起来更整洁,但确实涉及解析 CustomerName。

        var totalRecords = 0;
        Broker.GetBusinessObjectCollection<Customer>("CustomerName Like partialCustomerName ", "CustomerName", 0, 20, out totalRecords);
于 2011-06-02T19:05:11.760 回答