Using ASP.NET MVC without an ORM

CoolGravatar picture CoolGravatar · May 3, 2009 · Viewed 8.6k times · Source

In my ASP MVC application I'm using standard SQL (rather that Linq to SQL or other ORM) to query my database.

I would like to pass the database results to my view and iterate over the results in my view. But I'm not sure how to do this. Every example I've seen passes some string or uses L2S. I would like to pass something like nested Hashtables, but the only thing I can think of is to pass an SqlDataReader object to the view, but this sounds like a really bad idea.

How would I go about displaying my database results from a standard SQL query to my view? I would really like use Linq or other ORM, but requirements dictate we don't (don't ask me why, I don't understand). I'm doing this in VB. I'll try by best to convert any C# examples provided.

Answer

Steve Willcock picture Steve Willcock · May 3, 2009

You could create simple classes for the data you want to transfer and then populate a List of objects in your controller from a data reader manually, and then pass this to your View - e.g. (C# but this should be easy to convert)

// open your connection / datareader etc.

List<Customer> customers = new List<Customer>();

while(dataReader.Read())
{
 Customer c = new Customer();
 c.Id = dataReader.GetInt32(0);
 c.Name = dataReader.GetString(1);
 // etc (you might want to use string indexers instead of ints for the get methods)

 customers.Add(c);
}

// close and dispose your datareader / connection etc as usual

return View("List", customers);