cc0
cc0

Reputation: 1950

Making flexible C# code in MVC2 for Stored Procedures

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;

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).

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

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.

Upvotes: 0

Views: 945

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039578

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<string>.

Upvotes: 1

Related Questions