c# - EF Generic Repository Multiple Includes -
idea have 1 generic repository work entities. managed that, if need have method should include 1 or more other entities there problem me. have put idea in code, not working me. have been thinking use aggregate function in ef, have never use. can give me direction how can manage ?
public interface irepository<t> t : baseentity { ienumerable<t> getall(); t get(int64 id); void insert(t entity); void delete(t entity); task<bool> savechangesasync(); t searchbyname(expression<func<t, bool>> predicate); ienumerable<t> getall(string[] includes); } public class repository<t> : irepository<t> t : baseentity { private entities.appcontext _context; private dbset<t> entities; public repository(entities.appcontext context) { _context = context; entities = _context.set<t>(); } public void delete(t entity) { if (entity == null) { throw new argumentnullexception("entity"); } entities.remove(entity); } public t get(long id) { return entities.singleordefault(s => s.id == id); } public ienumerable<t> getall() { return entities.tolist(); } public ienumerable<t> getall(string[] includes) { foreach (string include in includes) { entities.include(include); } return entities; } public void insert(t entity) { if (entity == null) { throw new argumentnullexception("entity"); } entities.add(entity); } public async task<bool> savechangesasync() { try { return (await _context.savechangesasync()) > 0; } catch (exception ex) { return false; } } public t searchbyname(expression<func<t, bool>> predicate) { return entities.where(predicate).singleordefault(); } }
you have fallen in typical trap of calling method returns , ignoring result. line entities.include(include);
nothing - similar entities.where(...);
, entities.select(...);
etc.
the correct code this:
var query = entities.asqueryable(); foreach (var include in includes) query = query.include(include); return query;
or single line aggregate
:
return includes.aggregate(entities.asqueryable(), (query, path) => query.include(path));
Comments
Post a Comment