2011-06-02 10 views
1

我需要限制從數據庫中返回的客戶博的數量,因爲我正在尋找部分客戶名稱,並且此刻在搜索時獲得600多個博客爲一個'。我想此刻的限制這20我的代碼是在Habanero我將如何限制從數據庫返回的對象的數量

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

回答

1

直到在那裏,但沒有給出正確的語法。 代理用於從當前數據訪問器加載集合,而不是用於創建新集合。所以代碼將是:

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

這應該做到這一點! 請將答案直接授予Till,而不是我。他做了最多的研究。我只是糾正語法:)

編輯: 後低於約醜陋的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; 
} 

第二個參數是要排序的字段,這對於有限制的提取是必要的。希望這可以幫助。

+0

非常好,我正在尋找。 – Andrew 2011-06-02 14:40:00

+0

yikes什麼是醜陋的api – 2011-06-02 14:46:06

+0

是的我更喜歡下面答案中的那個。這個使用lambdas的Create.Criteria是非常新的,據我所知,這就是Linq to Habanero在幕後使用的東西。我不確定這是否打算成爲API。 – GloryDev 2011-06-02 19:05:56

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); 
} 
+0

感謝這個工程,但它似乎使調用數據庫。 – Andrew 2011-06-02 14:39:33

+0

是的,這將調用數據庫並在代理方法上加載所有客戶,然後使用條件和限制重新加載該集合。 – 2011-06-03 08:16:08

1

Andrew 你總是可以做到這一點看起來有點整潔,但確實涉及到解析客戶名稱 。

 var totalRecords = 0; 
     Broker.GetBusinessObjectCollection<Customer>("CustomerName Like partialCustomerName ", "CustomerName", 0, 20, out totalRecords); 
+0

啊,真棒,我看到這個語法也被Broker支持。我更喜歡這個語法來解決我的問題:) – 2011-06-03 08:27:14

相關問題