c# - Can you wrap a Func<EFContext, TResult> inside an Entities Context for reuse? -


i curious on reuse pattern may possible , wanted see if others have tried it. have these example of standard ef 6.1.3 returns:

private ienumerable<typetran> gettypes() {   using (var context = new expensesentities())   {     return context.tdtype.select(x => new typetran(x.typeid, x.description)).where(x => x.typeid != 3);   } }  private list<category> getcurrentcategories() {   using (var context = new expensesentities())   {     return context.tdcategory.select(x => new category(x.categoryid, x.description)).tolist();   } } 

don't worry typetran or category. suffice pocos , anything. abstracting layer removal of ef can have more after market effects on model object without effecting t4 generated objects database. model works fine there lot more retrieval patterns curious if like:

private treturn runcontextwithoption<treturn>(func<expensesentities, treturn> func) {   using (var context = new expensesentities())   {     return func.invoke(context);   } } 

but when attempt run doing syntax wrong , not seeing way use context without pre defining it.

//wrong won't run private list<typetran> gettypes() {   var cont = new expensesentities();   return runcontextwithoption<list<typetran>>((cont) => cont.tdtype.select(x => new typetran(x.typeid, x.description)).where(x => x.typeid != 3));  } 

so becomes chicken or egg, want context auto invoked helper, yet cannot need in arg appears. has else tried similar make repo pattern merely less lines of code? may bad practice less lines of code , using private helpers whenever possible rather repeating using(var context...) ad infinitum.

basically need. i've included optional where clause , pretty trivial include, say, orderby too:

public ienumerable<tentity> getentities<tentity>(     expression<func<tentity, bool>> predicate = null)     tentity : class {     using (var context = new expensesentities())     {         iqueryable<tentity> data = context.set<tentity>();         if (predicate != null)         {             data = data.where(predicate);         }          return data.tolist();     } } 

and call this:

var diedon = datetime.now.adddays(-30); var zombiesolderthan30days = getentities<zombie>(z =>      z.name == "bob" && z.diedon > diedon);  var allzombies = getnentities<zombie>(); 

Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -