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?