.NET/Mono Database Access—Easy column access?

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?

Answers


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.


Need Your Help

Get the innermost array in PHP

php

Below shown is my posted data from a form. Since i used a multiform approach,i got the posted data as an array. I want to save each value in to the database,ie 1,2,3.etc since it is the attribute

How to create an NDEF message that erases a NFC tag

android nfc ndef

I am creating an NFC application. I am a noob at Android this is my 2nd application. I was wondering if anyone knows how to create a message that erases the NFC tag. This function is seen in applic...