PostgreSQL · Retrieve

Find a record by id, key or columns

The three ways to find one record, in four scenarios: by id, by a declared key, by any columns, and what happens when columns match more than one row.

Set up for this page

Besides the sample itself, it uses SampleContext.cs (the dbContext every sample is given); SampleOutput.cs (Step and Show, which print), in the files below.

Before scenario 1 the sample runs this, so the service and the rows the scenarios use are there:

Set up
var service = new ArxPgDbService(connectionString, ArxSchemaCatalog.Create()
    .Table("contact", ArxIdColumn.Generated<long>("id")).Key("contact", "email")
    .Build());
var contacts = new List<ArxEntity>();
foreach (var (first, email) in new[] { ("Ines", "ines.r401@example.com"), ("Ivo", "ivo.r401@example.com") })
{
    var contact = new ArxEntity("contact");
    contact["first_name"] = first;
    contact["last_name"] = "Find-R401";
    contact["email"] = email;
    contacts.Add(contact);
}
var ids = await service.CreateMultipleAsync(contacts);

1 By id

By id, through an entity: the same as RetrieveAsync("contact", id).

Already in scope: service (ArxPgDbService), id (ArxRecordId)

C#
var match = new ArxEntity("contact") { RecordId = id };

var read = await service.RetrieveAsync(match, new ArxRetrieveOptions { Columns = new ArxColumnSet("first_name") }) ?? throw new InvalidOperationException("The record isn't there.");

Console.WriteLine($"{read["first_name"]}");

Check it in the database

SQL

Run it in any SQL tool connected to the database, after the code has run.

SELECT first_name
FROM contact
WHERE email = 'ines.r401@example.com';

Expect: 1 row, Ines.

2 By a declared key

By the declared key: the email is unique, so it finds one record.

Already in scope: service (ArxPgDbService)

C#
var match = new ArxEntity("contact");
match["email"] = "ivo.r401@example.com";

var read = await service.RetrieveAsync(match, new ArxRetrieveOptions { Match = ArxMatch.Key("email"), Columns = new ArxColumnSet("first_name") }) ?? throw new InvalidOperationException("The record isn't there.");

Console.WriteLine($"{read["first_name"]}");

Check it in the database

SQL

Run it in any SQL tool connected to the database, after the code has run.

SELECT first_name
FROM contact
WHERE email = 'ivo.r401@example.com';

Expect: 1 row, Ivo.

3 By any columns

By any columns: the first name and last name together, no declaration needed.

Already in scope: service (ArxPgDbService)

C#
var match = new ArxEntity("contact");
match["first_name"] = "Ines";
match["last_name"] = "Find-R401";

var read = await service.RetrieveAsync(match, new ArxRetrieveOptions { Match = ArxMatch.Columns("first_name", "last_name"), Columns = new ArxColumnSet("email") }) ?? throw new InvalidOperationException("The record isn't there.");

Console.WriteLine($"{read["email"]}");

Check it in the database

SQL

Run it in any SQL tool connected to the database, after the code has run.

SELECT email
FROM contact
WHERE first_name = 'Ines' AND last_name = 'Find-R401';

Expect: 1 row, ines.r401@example.com.

4 Several rows

A Retrieve answers one record: columns that match two rows are ARX2003. Use RetrieveMultiple for many.

Already in scope: service (ArxPgDbService)

C#
var match = new ArxEntity("contact");
match["last_name"] = "Find-R401";

try
{
    await service.RetrieveAsync(match, new ArxRetrieveOptions { Match = ArxMatch.Columns("last_name") });
}
catch (ArxException error) when (error.Code == ArxErrorCode.MultipleRecordsMatched)
{
    Console.WriteLine($"{error.Code}");
}

Check it in the database

SQL

Run it in any SQL tool connected to the database, after the code has run.

SELECT count(*)
FROM contact
WHERE last_name = 'Find-R401';

Expect: 2: that's why one record couldn't be returned.

Run the complete sample

The code above comes from one program, built in a fresh project and run against the database. To run it yourself, here is every file and step.

The program, its files and how to run it

Run it locally

  1. .NET SDK: .NET SDK 10.0.100 or later 10.0.x (target net10.0).
  2. Create the project:
    Terminal
    dotnet new console -n ArxSample -f net10.0
    cd ArxSample
  3. Install the packages:
    Terminal
    dotnet add package ARX.SDK.PostgreSql --version 1.0.0-rc.1
  4. Database: a PostgreSQL 16 (tested with 16.15) database with the sample schema.
  5. Configuration: set ARX_SAMPLES_POSTGRESQL to its connection string. Nothing is hard-coded.
  6. Source code: replace Program.cs and add the 3 other files below, with the file names shown.
  7. Run it:
    Terminal
    dotnet run
  8. Expected output: below.

The files

Program.cs

Runs the sample. Generated for this page; it reads the connection string from the environment.

using ArxSamples.PostgreSql;
using ArxSamples.PostgreSql.Operations.Retrieve.Basics;

// The connection string comes from the environment, never from the code (see "Configure the connection").
var connectionString = Environment.GetEnvironmentVariable("ARX_SAMPLES_POSTGRESQL")
    ?? throw new InvalidOperationException("Set the ARX_SAMPLES_POSTGRESQL environment variable to your PostgreSQL connection string.");

await new Basic3_HowToFindTheRow().RunAsync(new SampleContext(connectionString));
Basic3_HowToFindTheRow.cs

The sample, as it is in the repository.

using ARX.SDK;
using ARX.SDK.PostgreSql.Services;
using ARX.SDK.Services;

using static ArxSamples.PostgreSql.SampleOutput;

namespace ArxSamples.PostgreSql.Operations.Retrieve.Basics;

/// <summary>
/// The three ways to find one record, in four scenarios: by id, by a declared key, by any
/// columns, and what happens when columns match more than one row.
/// </summary>
public sealed class Basic3_HowToFindTheRow : ISample
{
    public string Name => "retrieve-basics-3-how-to-find-the-row";

    public string Title => "Find a record by id, key or columns";

    public async Task RunAsync(SampleContext dbContext)
    {
        var service = new ArxPgDbService(dbContext.ConnectionString, ArxSchemaCatalog.Create()
            .Table("contact", ArxIdColumn.Generated<long>("id")).Key("contact", "email")
            .Build());

        var contacts = new List<ArxEntity>();

        foreach (var (first, email) in new[] { ("Ines", "ines.r401@example.com"), ("Ivo", "ivo.r401@example.com") })
        {
            var contact = new ArxEntity("contact");
            contact["first_name"] = first;
            contact["last_name"] = "Find-R401";
            contact["email"] = email;
            contacts.Add(contact);
        }

        var ids = await service.CreateMultipleAsync(contacts);

        await Scenario1_ByIdAsync(service, ids[0]);

        await Scenario2_ByADeclaredKeyAsync(service);

        await Scenario3_ByAnyColumnsAsync(service);

        await Scenario4_ColumnsThatMatchSeveralRowsAsync(service);
    }

    /// <summary>1. By id, through an entity: the same as RetrieveAsync("contact", id).</summary>
    private static async Task Scenario1_ByIdAsync(ArxPgDbService service, ArxRecordId id)
    {
        Step("1. By id");

        var match = new ArxEntity("contact") { RecordId = id };

        var read = await service.RetrieveAsync(match, new ArxRetrieveOptions { Columns = new ArxColumnSet("first_name") }) ?? throw new InvalidOperationException("The record isn't there.");

        Show($"{read["first_name"]}");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT first_name
         * FROM contact
         * WHERE email = 'ines.r401@example.com';
         * -- Expect: 1 row, Ines.
         * ===========================================================
         */
    }

    /// <summary>2. By the declared key: the email is unique, so it finds one record.</summary>
    private static async Task Scenario2_ByADeclaredKeyAsync(ArxPgDbService service)
    {
        Step("2. By a declared key");

        var match = new ArxEntity("contact");
        match["email"] = "ivo.r401@example.com";

        var read = await service.RetrieveAsync(match, new ArxRetrieveOptions { Match = ArxMatch.Key("email"), Columns = new ArxColumnSet("first_name") }) ?? throw new InvalidOperationException("The record isn't there.");

        Show($"{read["first_name"]}");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT first_name
         * FROM contact
         * WHERE email = 'ivo.r401@example.com';
         * -- Expect: 1 row, Ivo.
         * ===========================================================
         */
    }

    /// <summary>3. By any columns: the first name and last name together, no declaration needed.</summary>
    private static async Task Scenario3_ByAnyColumnsAsync(ArxPgDbService service)
    {
        Step("3. By any columns");

        var match = new ArxEntity("contact");
        match["first_name"] = "Ines";
        match["last_name"] = "Find-R401";

        var read = await service.RetrieveAsync(match, new ArxRetrieveOptions { Match = ArxMatch.Columns("first_name", "last_name"), Columns = new ArxColumnSet("email") }) ?? throw new InvalidOperationException("The record isn't there.");

        Show($"{read["email"]}");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT email
         * FROM contact
         * WHERE first_name = 'Ines' AND last_name = 'Find-R401';
         * -- Expect: 1 row, ines.r401@example.com.
         * ===========================================================
         */
    }

    /// <summary>4. A Retrieve answers one record: columns that match two rows are ARX2003. Use RetrieveMultiple for many.</summary>
    private static async Task Scenario4_ColumnsThatMatchSeveralRowsAsync(ArxPgDbService service)
    {
        Step("4. Several rows");

        var match = new ArxEntity("contact");
        match["last_name"] = "Find-R401";

        try
        {
            await service.RetrieveAsync(match, new ArxRetrieveOptions { Match = ArxMatch.Columns("last_name") });
        }
        catch (ArxException error) when (error.Code == ArxErrorCode.MultipleRecordsMatched)
        {
            Show($"{error.Code}");
        }

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT count(*)
         * FROM contact
         * WHERE last_name = 'Find-R401';
         * -- Expect: 2: that's why one record couldn't be returned.
         * ===========================================================
         */
    }
}
SampleContext.cs

What every sample is given: the connection string (and the ISample interface the samples implement).

namespace ArxSamples.PostgreSql;

/// <summary>One documentation sample: a scenario a real application has, shown end to end.</summary>
public interface ISample
{
    /// <summary>The name to run it alone: <c>dotnet run -- &lt;name&gt;</c>.</summary>
    string Name { get; }

    /// <summary>One line on what it shows.</summary>
    string Title { get; }

    Task RunAsync(SampleContext dbContext);
}

/// <summary>
/// What a sample is given. Every sample gets the connection string; the application's service and catalog
/// (SampleContext.Application.cs) and the plain Npgsql read-back helper (SampleContext.Direct.cs) live in their own
/// files, so a sample needs only the files it uses.
/// </summary>
public sealed partial class SampleContext
{
    public SampleContext(string connectionString)
    {
        ConnectionString = connectionString;
    }

    public string ConnectionString { get; }
}
SampleOutput.cs

How the samples print: Step for each scenario, Show for what it did, ShowError for an error caught on purpose.

using ARX.SDK;

namespace ArxSamples.PostgreSql;

/// <summary>How the samples print: a numbered step for each scenario, then what it did.</summary>
public static class SampleOutput
{
    /// <summary>The start of a scenario: <c>Step("1. By the id Create returned")</c>.</summary>
    public static void Step(string text) => Console.WriteLine($"  > {text}");

    /// <summary>What the scenario did.</summary>
    public static void Show(string text) => Console.WriteLine($"      {text}");

    /// <summary>An ARX error the scenario caught on purpose.</summary>
    public static void ShowError(ArxException exception)
        => Console.WriteLine($"      caught {exception.GetType().Name}: {exception.Message}");
}

Expected output

What dotnet run printed when the sample was verified, on a freshly created sample schema. Ids differ when the tables already hold rows.

Output
  > 1. By id
      Ines
  > 2. By a declared key
      Ivo
  > 3. By any columns
      ines.r401@example.com
  > 4. Several rows
      MultipleRecordsMatched