2015-05-09 52 views
2

我使用c#winforms。我使用實體框架6.如何在高性能的實體框架上使用lambda表達式

在我的解決方案中,我有2個項目A.BLL & A.DAL名稱。 (A.DAL加在A.BLL參考)

A.DAL項目我有以下方法:

public decimal Sum(Func<ml_doc, bool> predicate, Func<ml_doc, decimal> sumColumn) 
{ 
    try 
    { 
     using (dbEnteties = new Entities(Connection.CustomEntityConnection)) 
     { 
      dbEnteties.ContextOptions.LazyLoadingEnabled = true; 
      var dbe = dbEnteties.ml_doc; 
      return dbe.Where(predicate).Sum(sumColumn); 
     } 
    } 
    catch (Exception exp) 
    { 
     throw exp; 
    } 
} 

A.BLL的項目,我有以下方法(上A.DAL項目使用數總和法) :

public decimal GetSum(long AccId, int? CntId, short BranchId, int BeginNumber) 
{ 
    try 
    { 
     using (dal = new DAL.DocDA()) 
     { 
      // Sum method referenced from A.DAL project 
      return dal.Sum(
       x => 
       x.acc_id == AccId && 
       x.cnt_id.Equals(CntId) && 
       x.ml_doc_hdr.branch_id == BranchId && 
       x.ml_doc_hdr.number >= BeginNumber 
       , 
       y => y.price); 
     } 
    } 
    catch (Exception exp) 
    { 
     throw exp; 
    } 
} 

當我使用GetSum方法(在A.BLL項目),我得到的例外情況:

。已經有個相關聯的打開的DataReader是必須首先關閉的命令。

爲了解決這個例外,我添加MultipleActiveResultSets =真我的連接字符串,這種方法非常slowy(例如3秒)。

下我的方法上A.DAL項目創建:

public decimal Sum2(long AccId, int? CntId, short BranchId, int BeginNumber) 
{ 
    try 
    { 
     using (dbEnteties = new Entities(Connection.CustomEntityConnection)) 
     { 
      dbEnteties.ContextOptions.LazyLoadingEnabled = true; 
      var resultQuery = dbEnteties.ml_doc.Where(
       x => 
       x.acc_id == AccId && 
       x.cnt_id.Equals(CntId) && 
       x.ml_doc_hdr.branch_id == BranchId && 
       x.ml_doc_hdr.number >= BeginNumber 
       ); 

      if (resultQuery.Count() != 0) 
      { 
       return resultQuery.Sum(x => x.price); 
      } 

      return 0; 
     } 
    } 
    catch (Exception exp) 
    { 
     throw exp; 
    } 
} 

當我使用上法(SUM2)這項工作很好和非常快的(例如0.003秒)

什麼是SUM2之間diffrence (在A.DAL項目上)& GetSum(在A.BLL projetc上)方法(似乎有相同的)?

如何更改GetSum方法以高性能工作?

回答

5

這一個:

public decimal Sum(Func<ml_doc, bool> predicate, Func<ml_doc, decimal> sumColumn) 
{ 
    try 
    { 
     using (dbEnteties = new Entities(Connection.CustomEntityConnection)) 
     { 
      dbEnteties.ContextOptions.LazyLoadingEnabled = true; 
      var dbe = dbEnteties.ml_doc; 
      return dbe.Where(predicate).Sum(sumColumn); 
     } 
    } 
    catch (Exception exp) 
    { 
     throw exp; 
    } 
} 

加載完整ml_doc表從本地SQL服務器,然後執行Where()Sum()操作本地。

這是因爲你的LINQ表達式使用兩個Func<>代表,所以不是使用

它採用

嘗試將其更改爲:

public decimal Sum(Expression<Func<ml_doc, bool>> predicate, Expression<Func<ml_doc, decimal>> sumColumn) 

Sum2方法來代替,通過使用直接一些lambda函數,採用Queryable.*方法,因爲lambda函數被解釋爲Expression<>

+0

非常感謝,這項工作非常好 –

相關問題