c# - asp.net mvc data logic structure -
so have bunch of entity models.
lots of controllers , views , controllers go , linq query , making available view.
however lets have model users
and have linq query active users
putting in controller might fine if done once, want repeat it, im wondering correct place putting model specific queries.
ideally controller says users.getactiveusers() or similar.
you should repository pattern.
the repository pattern allows abstract database logic , reduce redundancy of common data calls. since formulating linq queries often, why not put them 1 common class?
public class userrepository { private readonly _dbcontext mydbcontext; public ienumberable<user> getactiveusers() { // whatever find active users return _dbcontext.where(user => user.active == true); } }
now can inject repository controller.
public class homecontroller : controller { private readonly userrepository _userrepo; public homecontroller() { _userrepo = new userrepository(); } public actionresult index() { var activeusers = _userrepo.getactiveusers(); return view(activeusers); } }
the above implementation solve problem, tightly couple controller repository. solution decouple them use interface userrepository , use dependency injection (with ninject, unity, autofaq or whatever) resolve type interface.
Comments
Post a Comment