Main Contents

Retrieving Data Without the Dataset With Custom SQL

Schotime @ February 12, 2009

.NET

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


book mark Retrieving Data Without the Dataset With Custom SQL in del.icio.us submit Retrieving Data Without the Dataset With Custom SQL to digg.com


2 Comments

  1. Retrieving Data Without the Dataset With Custom SQL - Adam Schroder February 12, 2009 @ 8:51 pm

    [...] 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. Click here to see the solution. [...]

  2. Richard Kimber February 16, 2009 @ 6:32 am

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

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Feed
24,360 spam comments
blocked by
Akismet