PostgreSQL · Retrieve
Retrieve one record
The smallest read: one record, in three scenarios. The usual way first (the id CreateAsync returned, and the columns you want), then a text id, then an id nobody has: Retrieve returns null, not an error.
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.
1 By the id Create returned
The usual way: the table, the id Create returned, and the columns to read.
Already in scope: connectionString (string)
var service = Service(connectionString);
var account = new ArxEntity("account");
account["name"] = "Northwind Traders";
account["account_number"] = "ACC-R101";
account["employee_count"] = 120;
ArxRecordId id = await service.CreateAsync(account);
ArxEntity read = await service.RetrieveAsync("account", id, new ArxColumnSet("name", "employee_count")) ?? throw new InvalidOperationException("The account record isn't there.");
// The id is always read too, so read.RecordId can update or delete this record later.
Console.WriteLine($"{read["name"]}, {read["employee_count"]} employees, RecordId {read.RecordId}");Defined once in this sample.
private static ArxPgDbService Service(string connectionString) => new ArxPgDbService(connectionString, ArxSchemaCatalog.Create()
.Table("account", ArxIdColumn.Generated<long>("id"))
.Table("country", ArxIdColumn.Supplied<string>("code"))
.Build());Check it in the database
Run it in any SQL tool connected to the database, after the code has run.
SELECT name, employee_count
FROM account
WHERE account_number = 'ACC-R101';Expect: 1 row, Northwind Traders, 120: what Retrieve returned.
2 A text id
A text id: a country by its code. Without columns, every column is read.
Already in scope: connectionString (string)
var service = Service(connectionString);
var iceland = new ArxEntity("country");
iceland["code"] = "IS";
iceland["name"] = "Iceland";
await service.CreateAsync(iceland);
ArxEntity read = await service.RetrieveAsync("country", "IS") ?? throw new InvalidOperationException("The country record isn't there.");
Console.WriteLine($"{read["code"]} is {read["name"]} ({read.Attributes.Count} columns)");Defined once in this sample.
private static ArxPgDbService Service(string connectionString) => new ArxPgDbService(connectionString, ArxSchemaCatalog.Create()
.Table("account", ArxIdColumn.Generated<long>("id"))
.Table("country", ArxIdColumn.Supplied<string>("code"))
.Build());Check it in the database
Run it in any SQL tool connected to the database, after the code has run.
SELECT code, name
FROM country
WHERE code = 'IS';Expect: 1 row, IS, Iceland.
3 An id nobody has
An id that doesn't exist: null, so "is it there?" needs no try/catch.
Already in scope: connectionString (string)
var service = Service(connectionString);
ArxEntity? read = await service.RetrieveAsync("account", 999_999_999L);
Console.WriteLine($"{(read == null ? "null" : "found")}");Defined once in this sample.
private static ArxPgDbService Service(string connectionString) => new ArxPgDbService(connectionString, ArxSchemaCatalog.Create()
.Table("account", ArxIdColumn.Generated<long>("id"))
.Table("country", ArxIdColumn.Supplied<string>("code"))
.Build());Check it in the database
Run it in any SQL tool connected to the database, after the code has run.
SELECT count(*)
FROM account
WHERE id = 999999999;Expect: 0.
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
- .NET SDK: .NET SDK 10.0.100 or later 10.0.x (target
net10.0). - Create the project:
Terminal dotnet new console -n ArxSample -f net10.0 cd ArxSample - Install the packages:
Terminal dotnet add package ARX.SDK.PostgreSql --version 1.0.0-rc.1 - Database: a PostgreSQL 16 (tested with 16.15) database with the sample schema.
- Configuration: set
ARX_SAMPLES_POSTGRESQLto its connection string. Nothing is hard-coded. - Source code: replace
Program.csand add the 3 other files below, with the file names shown. - Run it:
Terminal dotnet run - Expected output: below.
The files
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 Basic1_RetrieveOneRecord().RunAsync(new SampleContext(connectionString));
The sample, as it is in the repository.
using ARX.SDK.PostgreSql.Services;
using ARX.SDK.Services;
using static ArxSamples.PostgreSql.SampleOutput;
namespace ArxSamples.PostgreSql.Operations.Retrieve.Basics;
/// <summary>
/// The smallest read: one record, in three scenarios. The usual way first (the id CreateAsync returned, and the columns
/// you want), then a text id, then an id nobody has: Retrieve returns null, not an error.
/// </summary>
public sealed class Basic1_RetrieveOneRecord : ISample
{
public string Name => "retrieve-basics-1-retrieve-one-record";
public string Title => "Retrieve one record";
public async Task RunAsync(SampleContext dbContext)
{
await Scenario1_ByTheIdCreateReturnedAsync(dbContext.ConnectionString);
await Scenario2_ATextIdAsync(dbContext.ConnectionString);
await Scenario3_NotFoundIsNullAsync(dbContext.ConnectionString);
}
private static ArxPgDbService Service(string connectionString) => new ArxPgDbService(connectionString, ArxSchemaCatalog.Create()
.Table("account", ArxIdColumn.Generated<long>("id"))
.Table("country", ArxIdColumn.Supplied<string>("code"))
.Build());
/// <summary>1. The usual way: the table, the id Create returned, and the columns to read.</summary>
private static async Task Scenario1_ByTheIdCreateReturnedAsync(string connectionString)
{
Step("1. By the id Create returned");
var service = Service(connectionString);
var account = new ArxEntity("account");
account["name"] = "Northwind Traders";
account["account_number"] = "ACC-R101";
account["employee_count"] = 120;
ArxRecordId id = await service.CreateAsync(account);
ArxEntity read = await service.RetrieveAsync("account", id, new ArxColumnSet("name", "employee_count")) ?? throw new InvalidOperationException("The account record isn't there.");
// The id is always read too, so read.RecordId can update or delete this record later.
Show($"{read["name"]}, {read["employee_count"]} employees, RecordId {read.RecordId}");
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* SELECT name, employee_count
* FROM account
* WHERE account_number = 'ACC-R101';
* -- Expect: 1 row, Northwind Traders, 120: what Retrieve returned.
* ===========================================================
*/
}
/// <summary>2. A text id: a country by its code. Without columns, every column is read.</summary>
private static async Task Scenario2_ATextIdAsync(string connectionString)
{
Step("2. A text id");
var service = Service(connectionString);
var iceland = new ArxEntity("country");
iceland["code"] = "IS";
iceland["name"] = "Iceland";
await service.CreateAsync(iceland);
ArxEntity read = await service.RetrieveAsync("country", "IS") ?? throw new InvalidOperationException("The country record isn't there.");
Show($"{read["code"]} is {read["name"]} ({read.Attributes.Count} columns)");
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* SELECT code, name
* FROM country
* WHERE code = 'IS';
* -- Expect: 1 row, IS, Iceland.
* ===========================================================
*/
}
/// <summary>3. An id that doesn't exist: null, so "is it there?" needs no try/catch.</summary>
private static async Task Scenario3_NotFoundIsNullAsync(string connectionString)
{
Step("3. An id nobody has");
var service = Service(connectionString);
ArxEntity? read = await service.RetrieveAsync("account", 999_999_999L);
Show($"{(read == null ? "null" : "found")}");
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* SELECT count(*)
* FROM account
* WHERE id = 999999999;
* -- Expect: 0.
* ===========================================================
*/
}
}
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 -- <name></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; }
}
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.
> 1. By the id Create returned
Northwind Traders, 120 employees, RecordId 1
> 2. A text id
IS is Iceland (2 columns)
> 3. An id nobody has
null