2011年9月21日

[Entity Framework] Passing expressions thru methods

I want to have a “generic” entity method to does some routine tasks before actually query to the database, and I want this method to accept a Func<T,bool> as input paramater. So I wrote codes like this…

 

protected static TM_STD_APPLYFORM_DATA QueryApplyFormDataFunc<TM_STD_APPLYFORM_DATA, bool> where) {
using (var db = new DBEntities()) {
var table = db.TM_STD_APPLYFORM_DATA.Where(where);
return table.SingleOrDefault();
}
}



After some tests, I realized that this function seems to have returns whole data in that table and does a “In memory” filter hence lead to poor performance. Solution is pretty easy, since Linq to Entity cannot generate correct SQL, the only thing we need to do is to make it know exactally what we want. So simply change the input paramter type to Expressions<Func<T,bool>> like this.



 




protected TM_STD_APPLYFORM_DATA QueryApplyFormData(System.Linq.Expressions.Expression<Func<TM_STD_APPLYFORM_DATA, bool>> where, ) {
using(var db = new DBEntities()){
return db.TM_STD_APPLYFORM_DATA.Where(where).SingleOrDefault();
}
}

沒有留言:

Blog Archive

About Me