c# - linq-to-sql asp mvc - where access to the data context? -
good day everyone!
currently working on project in asp-mvc 2 linq sql handle database.
i see many documentation linq sql in asp mvc, question is, exactly access data context? place better performance?
for example, have mydbdatacontext
class
i can define in controllers
public class imaginarycontroller : controller { mydbdatacontext context = new mydbdatacontext (); public actionresult index() { var list = // code read context return view(list); } } .......
or, in action methods
public class imaginarycontroller : controller { public actionresult index() { mydbdatacontext context = new mydbdatacontext (); var list = /* code read context */; return view(list); } public actionresult create() { //but create need reference mydbdatacontext context = new mydbdatacontext (); var list = /* code read context */; return view(list); } }
another option create class access data
public class accestobd{ //maybe private mydbdatacontext current; public static mydbdatacontext getcontext(){ return current; } }
or more complex implementing singleton pattern in c#
what best solution? , why?. answers.
ideally want use dependency injection this. in it's basic form can inject database context controller constructor. way won't have create new instances of context in of controllers/actions etc..
a great example of doing can found here:
asp.net mvc 4 dependency injection - hands on lab
it helps separate direct access data logic controllers/actions - super important should need change method of data storage etc..
Comments
Post a Comment