2015-05-09 50 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

非常感谢,这项工作非常好 –

相关问题