Making flexible C# code in MVC2 for Stored Procedures

By : cc0
Source: Stackoverflow.com
Question!

Thanks to Darin Dimitrov's suggestion I got a big step further in understanding good MVC code, but I'm having some problems making it flexible.

I implemented Darin's suggested solution, and it works perfectly for single controllers. However I'm having some trouble implementing it with some flexibility. What I'm looking for is this;

  • To be able to make dynamic column names in json

Instead of using "Column1: 'value', ..." and "Column2: 'value', ..." inside the json, I'd like to use for example "id: 'value', ..." and "place: 'value' ..." for one stored procedure, and "animal" and "type" in another (inside the json format).

  • To be able to make dynamic amounts of columns dependent on which stored procedure is called

Some stored procedures I'll want to read more than 2 rows from, is there a smart way of accomplishing that?

  • To be able to make numeric (floats and integers) rows from the database be presented inside the json without quotes

Like this (name and age);

{
    Column1: "John",
    Column2: 53
},

I would be very grateful for any feedback and suggestions / code examples I can get here. Even imperfect ones.

By : cc0


Answers

How about using anonymous objects? So for example you could have a method in your repository that returns System.Object:

public interface IRepository
{
    object GetModel(int id);
}

Then depending on the stored procedure you are calling you would return a different anonymous type:

public class RepositorySql : IRepository
{
    public object GetModel(int id) 
    {
        // TODO: Call a stored procedure and depending on the procedure you are 
        // calling return a different anonymous type, for example:
        return new 
        {
            Column1 = "value1",
            Column2 = "value2",
        }
    }
}

and finally in your controller:

public ActionResult Index(int id)
{
    var model = _repository.GetModel(id);
    return Json(model);
}

Now of course the view consuming this action would need to know what columns are there in the JSON object. I would recommend you using some base type instead of System.Object from which other models would derive and that would contain common properties.

I don't really know your requirements but if it is simply a matter of returning some list of values that would vary based on the stored procedure you could simply return an IEnumerable



This video can help you solving your question :)
By: admin