c# - Entity Framework AddOrUpdate implementation -


i'm trying create extension method similar addorudpate.

the usage should this:

var student = context.students.getorcreate(     s => s.name,      new student() { name = "somename" }) 

if there user name should return it, otherwise should create new user.

this have:

public static tentity getorcreate<tentity>(     idbset<tentity> set,     expression<func<tentity, object>> identifierexpression,     tentity entity) tentity : class {     var func = identifierexpression.compile();     var id = func.invoke(entity);     var persistedentity = set.firstordefault(e => func.invoke(e) == id);      if (persistedentity != null)     {         return persistedentity;     }      return set.add(entity); } 

but can't call invoke using linq entities.
how should use identifierexpresion?

use create new expression can pass firstordefault , let ef provider handle converting expression sql. new expression test equality id retrieved compiled , invoked expression. this:

var equalityexpr = expression.equal(identifierexpression.body, expression.constant(id)); var findmatchexpr = expression.lambda<func<tentity, bool>>(equalityexpr, identifierexpression.parameters); var persistedentity = set.firstordefault(findmatchexpr); 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -