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
include
s. 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
Post a Comment