Executing SQL queries in a Controller Action

帅比萌擦擦* 提交于 2019-12-23 15:53:35

问题


I have 5 separate SQL queries that I am executing in order in a controller action. This is the method I am using to execute them:

var entity = new TestEntities();

entity.Database.ExecuteSqlCommand("//SQL Query");

So, basically I have five ExecuteSqlCommand in a row with different queries that must execute in order and the code must continue to execute below them. Is there a better way to execute queries from inside a controller action? I am not sure the best way to do error handling with this current method.

Thanks!


回答1:


To start with look at creating a abstraction layer in between your controller and your database. An example of this is a repository, which will help when you come to testing. You can create mock repositories that you can use to in your unit tests rather than testing against your actual database.

You mention that you have 5 different database commands to fire. Look at the Unit of Work pattern which you can use to help track what you have changed and apply all of these changes to the database.

There is a good article on Microsoft's asp.net website about implementing the repository and unit of work.



来源:https://stackoverflow.com/questions/31833080/executing-sql-queries-in-a-controller-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!