c# - Add Include to repository -
i have working repository.
public class repository<tentity> : irepository<tentity> tentity : class { protected readonly dbcontext context; public repository(dbcontext context) { context = context; } public tentity get(int id) { return context.set<tentity>().find(id); } public ienumerable<tentity> getall() { return context.set<tentity>().tolist(); } public ienumerable<tentity> find(expression<func<tentity, bool>> predicate) { return context.set<tentity>().where(predicate); } public tentity singleordefault(expression<func<tentity, bool>> predicate) { return context.set<tentity>().singleordefault(predicate); } public void add(tentity entity) { context.set<tentity>().add(entity); } public void remove(tentity entity) { context.set<tentity>().remove(entity); } }
as read in coding repositories, don't add class until need it. now, need add include. found 1 in community use include() method in repository:
public static class includeextension { public static iqueryable<tentity> include<tentity>(this idbset<tentity> dbset, params expression<func<tentity, object>>[] includes) tentity : class { iqueryable<tentity> query = null; foreach (var include in includes) { query = dbset.include(include); } return query ?? dbset; } }
then, changed fit in code (as think) be:
public ienumerable<tentity> include(idbset<tentity> dbset, params expression<func<tentity, object>>[] includes) { ienumerable<tentity> query = null; foreach (var include in includes) { query = dbset.include(include); } return query ?? dbset; }
with direct access context, able write:
provinces = _cmsdbcontext.provinces.include(c => c.district).include(c => c.district.country).tolist();
but, repository, can't write:
provinces = currentunitofwork.provincerepository.include(c => c.district).include(c => c.district.country).tolist();
i got error:
cannot convert lambda expression type idbset<province> because not delegate type
what problem here, please.
i suspect code passing in lambda expression idbset parameter , can not convert type.
i have not been able test compiles, if method member of repository class try this.
public ienumerable<tentity> include(params expression<func<tentity, object>>[] includes) { idbset<tentity> dbset = context.set<tentity>(); ienumerable<tentity> query = null; foreach (var include in includes) { query = dbset.include(include); } return query ?? dbset; }