2015-08-27 59 views
2

我打循環中的數據庫。請建議我如何避免這種情況?打到循環中的數據庫

foreach (var assignedPricing in reviewingPricing) 
     { 
        var assignedUserId = _wfActivitySvc.GetPricingReviewer(assignedPricing.PricingID).UserId; 
        if (assignedUserId == UserId) 
         { 
          reviewingAssignedPricings.Add(assignedPricing); 
         } 
     } 
+4

發送列表到數據庫並在一次調用中進行批量插入 –

+0

您能舉出上面的示例代碼嗎? – user662285

+0

你使用什麼ORM? – Ofiris

回答

2

在你的數據庫服務創建一個新的查詢:

//Build an collection with just unique ids 
var priceIds = reviewingPricing.Select(x => x.PricingId).Distinct(); 

//Return a key/value collection with all priceId/UserId 
var reviewerMap = _wfActivitySvc.GetAllReviewersByPriceId(priceIds); 

//now you can loop without db queries 
foreach (var pricing in reviewingPricing) 
{ 
    var reviewer = reviewMap.FirstOrDefault(x => x.PricingId == pricing.PricingId); 
    if (reviewerMap == null) 
     continue; 
    if (reviewer.UserId == UserId) 
    { 
     reviewingAssignedPricings.Add(pricing); 
    } 
} 
0

1)您可能要在一次插入所有記錄。您可以創建存儲過程來執行此操作。如果你使用SQL服務器,你可以使用BulkInserter類:https://github.com/ronnieoverby/RonnieOverbyGrabBag/blob/master/BulkInserter.cs 對於生產我不得不在內部調整它來減少它的初始化時間,但對於不經常的批量插入Github版本就好了。 用例:

var bulkInserter = new BulkInserter<YourClass>(SqlConnection, "Table Name"); 
bulkInserter.Insert(reviewingAssignedPricings); 
bulkInserter.Flush(); 

2)如果該值與數據庫中每一次

_wfActivitySvc.GetPricingReviewer(assignedPricing.PricingID).UserId; 

讀取然後用外循環單呼取代它,以獲得從數據庫中的所有reviweres,然後添加到字典中(鍵= priceID ,value = reviewer),然後從循環內的字典中獲取審閱者。如果你使用簡單的List和.FirstOrDefault(),那麼它對列表中的100多個項目可能會明顯變慢。 jgauffin答案描述了這個想法。