我正在创建许多不同的控制器,一个与数据库中的每个存储过程相关。这些仅用于读取数据并使其以jSONcripts的JSON格式提供。
到目前为止我的代码看起来像这样,我想知道我是否错过了重用代码的机会,也许会做一些帮助类。我对OOP的经验太少了,所以在这里提供任何帮助和建议都会非常感激。
到目前为止,这是我的通用代码(已测试并正常工作);
using System;
using System.Configuration;
using System.Web.Mvc;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using Prototype.Models;
namespace Prototype.Controllers
{
public class NameOfStoredProcedureController : Controller
{
char[] lastComma = { ',' };
String oldChar = "\"";
String newChar = """;
StringBuilder json = new StringBuilder();
private String strCon = ConfigurationManager.ConnectionStrings["SomeConnectionString"].ConnectionString;
private SqlConnection con;
public StoredProcedureController()
{
con = new SqlConnection(strCon);
}
public string do_NameOfStoredProcedure(int parameter)
{
con.Open();
using (SqlCommand cmd = new SqlCommand("NameOfStoredProcedure", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@parameter", parameter);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
json.AppendFormat("[{0},\"{1}\"],", reader["column1"], reader["column2"]);
}
}
con.Close();
}
if (json.Length.ToString().Equals("0"))
{
return "[]";
}
else
{
return "[" + json.ToString().TrimEnd(lastComma) + "]";
}
}
//http://host.com/NameOfStoredProcedure?parameter=value
public ActionResult Index(int parameter)
{
return new ContentResult
{
ContentType = "application/json",
Content = do_NameOfStoredProcedure(parameter)
};
}
}
}
答案 0 :(得分:5)
我可能不会直接从控制器访问数据库,而是宁愿抽象这种访问。不是性能优化而是设计改进。因此,首先定义一个将保存存储过程结果的模型:
public class MyModel
{
public string Column1 { get; set; }
public string Column2 { get; set; }
}
然后定义一个存储库接口,该接口将包含此模型上的不同操作:
public interface IRepository
{
IEnumerable<MyModel> GetModel(int id);
}
接下来实现存储库:
public class RepositorySql : IRepository
{
public IEnumerable<MyModel> GetModel(int id)
{
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SomeConnectionString"].ConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "NameOfStoredProcedure";
cmd.Parameters.AddWithValue("@parameter", id);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return new MyModel
{
Column1 = reader["column1"].ToString(),
Column2 = reader["column2"].ToString()
};
}
}
}
}
}
最后你的控制器将使用存储库:
public class NameOfStoredProcedureController : Controller
{
private readonly IRepository _repository;
public NameOfStoredProcedureController(IRepository repository)
{
_repository = repository;
}
// Warning don't add this constructor. Use a DI framework instead.
// This kind of constructors are called Poor Man DI (see http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/07/03/how-not-to-do-dependency-injection-in-nerddinner.aspx)
// for more info on why this is bad.
public NameOfStoredProcedureController() : this(new RepositorySql())
{ }
public ActionResult Index(int parameter)
{
var model = _repository.GetModel(parameter);
// Use directly Json, no need to do the serialization manually
return Json(model);
}
}
答案 1 :(得分:2)