c# - Repository generic method GetById using eager loading -


i using entity framework , create generic getbyid method in repository class eager loading:

here method uses lazy-loading:

public virtual tentity getbyid(object id)   {     return dbset.find(id);   } 

i know method find not support eager loading, how possible modify method use eager loading, use method follows(for example):

_unitofwork.myrepository.getbyid(includeproperties: "users"); 

one possible way use firstordefault predicate on dbset includes. it's not hard build manually predicate using expression.equal method, main challenge how key property name. luckily can use objectcontext methods that, implementation (assuming have access concrete dbcontext instance):

public virtual tentity getbyid(object id, params string[] includeproperties) {     var propertyname = ((system.data.entity.infrastructure.iobjectcontextadapter)dbcontext).objectcontext         .createobjectset<tentity>().entityset.elementtype.keymembers.single().name;      var parameter = expression.parameter(typeof(tentity), "e");     var predicate = expression.lambda<func<tentity, bool>>(         expression.equal(             expression.propertyorfield(parameter, propertyname),             expression.constant(id)),         parameter);      var query = dbset.asqueryable();     if (includeproperties != null && includeproperties.length > 0)         query = includeproperties.aggregate(query, system.data.entity.queryableextensions.include);     return query.firstordefault(predicate); } 

Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -