.NET / Mono Access-Easy Database Access?

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

Let's say that I have a table created by the following operators CREATE TABLE

and INSERT

.

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);

      

As I understand it so far, I need (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 I would like to do 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'm just hiding something somewhere) that the best way to access the database is required and this is really cumbersome when you're going to be working with a lot of relationships ... so is there a way to do something closer to the last pseudocode?

0


source to share


2 answers


If you want to easily go to ORM framework.

If you want maximum performance this should do the trick. Just remember that caching is the fastest :)



The top example is also faster because there is no conversion.

+1


source


Hehe ... it turns out I should have just tried, not asked. Can't find any documentation to say it works, but it works.



0


source







All Articles