.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.


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.


Need Your Help

Playing Audio File from the directory in swift

ios audio swift

I am trying to save a audio file from a server to the users phone so they dont have to download it again its always there. I have almost everything but i am trying to test and see if the audio file

Unit testing function, how to implement call to mock object

angularjs unit-testing karma-jasmine

I'm writing a unit tests for a controller which has an angular scope function that when called, calls a parse.com framework function that makes a call to the parse server and returns the success