Retrieving Data Without the Dataset With Custom SQL

In my previous post I used custom sql query and transformed the results into a nested class. However you may have overlooked way I got the data into a class. It quite easy and will work with all database connectors that implement IDbConnection.

Here is how its done. We use the DataContext that came with and used by Linq2Sql.


public class RawData { public int MyId { get; set; } public string Name { get; set; } }


        DataContext dc = new DataContext(new MySqlConnection(connString));
        IEnumerable<RawData> rd = 
            dc.ExecuteQuery<RawData>("select myid, name from mytable where myid > ?",5);

And thats it. All the data from the mytable database table will get pushed into the IEnumerable<RawData> variable. As long as the names of the columns are the same as the class then this will work. This ExecuteQuery method also takes a parameters object argument which will replace the question marks with the variables specified.

It makes it very easy, especially since there isn’t a very good linq 2 mysql option out there yet and Entity Framework still doesn’t support it.

Cheers,
Adam

This entry was posted in .NET and tagged . Bookmark the permalink.

2 Responses to Retrieving Data Without the Dataset With Custom SQL

  1. Pingback: Retrieving Data Without the Dataset With Custom SQL - Adam Schroder

  2. Wow, that is really cool. I had no idea you could do this with DataContext.

Leave a comment