views:

214

answers:

2

I am not sure if I am missing something grotesquely obvious or what, but I can't seem to figure out how to efficiently access tables in a relational database. I am using PostgreSQL for the database server (and Npgsql for its access) and C# with Mono 2.0.

Say I have the table created by the following CREATE TABLE and INSERT statements.

CREATE TABLE foo (
  id UUID NOT NULL PRIMARY KEY,
  bar VARCHAR(20) NOT NULL,
  baz INT NOT NULL
)

INSERT INTO foo VALUES ('f42d3178-b900-11dd-ac23-001966607b2e', 'foo!', 1);

The way I understand it thus far, I have to (C#):

using(NpgsqlConnection dbc = new NpgsqlConnection(connectionString)) {
  using(NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM foo LIMIT 1", dbc)) {
    NpgsqlDataReader rdr = cmd.ExecuteReader();

    if(!rdr.HasRows())
      throw new Exception("No rows");

    rdr.Read();

    Guid id = rdr.GetGuid(0);
    string bar = rdr.GetString(1);
    int baz = rdr.GetString(2);
  }
}

But, what I would really like to do is something like the following pseudocode:

using(NpgsqlConnection dbc = new NpgsqlConnection(connectionString)) {
  using(NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM foo LIMIT 1", dbc)) {
    NpgsqlDataReader rdr = cmd.ExecuteReader();

    if(!rdr.HasRows())
      throw new Exception("No rows");

    rdr.Read();

    Guid id = (Guid)rdr["id"];
    string bar = (string)rdr["bar"];
    int baz = (int)rdr["baz"];
  }
}

It doesn't seem to me (and hopefully I am just missing something obvious somewhere) that the top method of database access is required, and that really is cumbersome when you are going to be working with lots of relations... so, is there a way to do something closer to the latter pseudocode?

A: 

Heh... turns out I should have just tried it instead of asking. Can't find any documentation to say that it works, but it seems to work.

Michael Trausch
+1  A: 

If you want easy go with an ORM framework.

If you want max performance this should work. Just remember caching is alwast fastest :)

Top example is also faster because there is no conversion.

Mischa Kroon
It turns out that the second one works a bit differently than I thought. at least for NpgsqlDataReader, the objects are already typed, and accessible as if they were a dictionary. So, for the example above, rdr["id"] is already a System.Guid. Very cool, I think, and just what the doctor ordered. :)
Michael Trausch