Optimizing C# code in MVC controller

旧巷老猫 提交于 2019-12-07 11:42:25

I probably wouldn't directly access the database from the controller but would rather abstract this access. Not really a performance optimization but design improvement. So start by defining a model that will hold the result of the stored procedure:

public class MyModel
{
    public string Column1 { get; set; }
    public string Column2 { get; set; }
}

Then define a repository interface that will contain the different operations on this model:

public interface IRepository
{
    IEnumerable<MyModel> GetModel(int id);
}

Next implement the repository:

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()
                    };
                }
            }
        }
    }
}

Finally your controller will use the repository:

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);
    }
}
kervin

Quite often I do things manually myself, but have you taken a look at JsonResult ( Example )?

And also JavaScriptSerializer?

And also JSON.Net?

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