I am new to the MVC concept and seperating Data from the controller logic. I am using Linq to Sql – and now I create a new instance of my DbContext , then use that to query the db from the controller. I have to do a lot of the same queries in different spots in my code – so my question is – Am I able to create a seperate class in my Model folder , create a new instance of my dbcontext in there, and create functions that query db in the class , make those functions public and then call them from any controller I want? I guess its a 2 part question , am I able to do this , and is this the preferred way to connect to db or do I just write all seperate code in different controllers?
Share
If you have to do similar/same queries many times, I recommend you compile your LINQ queries(The link is for LINQ to Entities, but basically the same idea for LINQ to SQL). It has much better performance from calling the query repeatedly. You can do something similar to the below snippet:
Basically you can just put these compiled queries in your
DbContextclass and then call it using theusingstatements.