Executing SQL queries in controller action
I have 5 separate SQL queries that I execute in order in a controller action. This is the method I use to accomplish them:
var entity = new TestEntities();
entity.Database.ExecuteSqlCommand("//SQL Query");
So basically I have five ExecuteSqlCommand
on a line with different requests to be executed in order and the code should continue to execute underneath them. Is there a better way to execute requests from within a controller action? I'm not sure what the best way to handle errors is with this current method.
Thank!
source to share
First, let's look at creating an abstraction layer between your controller and your database. An example of this is a repository to help you with testing. You can create mock repositories that you can use in your unit tests rather than testing your actual database.
You mentioned that you have 5 different database commands to run. Take a look at the Unit of Work , which you can use to keep track of what you have changed and apply all those changes to the database.
Microsoft's asp.net website has a good article about Repository and Unit of Work Implementation .
source to share