在Controller Action中执行SQL查询 [英] Executing SQL queries in a Controller Action

查看:318
本文介绍了在Controller Action中执行SQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有5个单独的SQL查询,这些查询按顺序在控制器操作中执行.这是我用来执行它们的方法:

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");

因此,基本上,我连续有五个ExecuteSqlCommand,它们具有必须按顺序执行的不同查询,并且代码必须在它们下面继续执行.有没有更好的方法可以从控制器操作内部执行查询?我不确定使用当前方法进行错误处理的最佳方法.

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.

谢谢!

推荐答案

首先来看一下在控制器和数据库之间创建一个抽象层.存储库就是一个例子,它会在您进行测试时提供帮助.您可以创建可在单元测试中使用的模拟存储库,而不是针对实际数据库进行测试.

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.

您提到要触发5个不同的数据库命令.查看工作单元模式,该模式可用于帮助您跟踪更改和应用的内容所有这些对数据库的更改.

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.

Microsoft的asp.net网站上有一篇很好的文章,内容关于实现存储库和工作单元 .

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

这篇关于在Controller Action中执行SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆