PostgreSQL · Update
Catch a record that doesn't exist
An update of a record that doesn't exist is an error, ARX2002 RecordNotFound, never silently nothing. Two scenarios: one record, and a list where one is missing.
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:
var service = new ArxPgDbService(connectionString, ArxSchemaCatalog.Create()
.Table("account", ArxIdColumn.Generated<long>("id"))
.Build());1 One record
The usual case: the id doesn't exist (deleted meanwhile, or a wrong id).
Already in scope: service (ArxPgDbService)
var change = new ArxEntity("account");
change["id"] = 999_999_998L;
change["name"] = "Nobody";
try
{
await service.UpdateAsync(change);
}
catch (ArxException error) when (error.Code == ArxErrorCode.RecordNotFound)
{
Console.WriteLine($"{error.Message}");
}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 name = 'Nobody';Expect: 0.
2 One of many
In a list, the error says how many entities matched no row, and nothing in the list was changed.
Already in scope: service (ArxPgDbService)
var account = new ArxEntity("account");
account["name"] = "Margie's Travel";
account["account_number"] = "ACC-U401";
var id = await service.CreateAsync(account);
var real = new ArxEntity("account");
real.RecordId = id;
real["name"] = "Margie's Travel Agency";
var ghost = new ArxEntity("account");
ghost["id"] = 999_999_997L;
ghost["name"] = "Ghost";
try
{
await service.UpdateMultipleAsync(new[] { real, ghost });
}
catch (ArxException error) when (error.Code == ArxErrorCode.RecordNotFound)
{
Console.WriteLine($"{error.Message}");
}Check it in the database
Run it in any SQL tool connected to the database, after the code has run.
SELECT name
FROM account
WHERE account_number = 'ACC-U401';Expect: 1 row, Margie's Travel: the real account wasn't renamed either.
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.Update.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_RecordNotFound().RunAsync(new SampleContext(connectionString));
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.Update.Basics;
/// <summary>
/// An update of a record that doesn't exist is an error, ARX2002 RecordNotFound, never silently nothing. Two scenarios:
/// one record, and a list where one is missing.
/// </summary>
public sealed class Basic3_RecordNotFound : ISample
{
public string Name => "update-basics-3-record-not-found";
public string Title => "Catch a record that doesn't exist";
public async Task RunAsync(SampleContext dbContext)
{
var service = new ArxPgDbService(dbContext.ConnectionString, ArxSchemaCatalog.Create()
.Table("account", ArxIdColumn.Generated<long>("id"))
.Build());
await Scenario1_OneRecordAsync(service);
await Scenario2_OneOfManyAsync(service);
}
/// <summary>1. The usual case: the id doesn't exist (deleted meanwhile, or a wrong id).</summary>
private static async Task Scenario1_OneRecordAsync(ArxPgDbService service)
{
Step("1. One record");
var change = new ArxEntity("account");
change["id"] = 999_999_998L;
change["name"] = "Nobody";
try
{
await service.UpdateAsync(change);
}
catch (ArxException error) when (error.Code == ArxErrorCode.RecordNotFound)
{
Show($"{error.Message}");
}
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* SELECT count(*)
* FROM account
* WHERE name = 'Nobody';
* -- Expect: 0.
* ===========================================================
*/
}
/// <summary>2. In a list, the error says how many entities matched no row, and nothing in the list was changed.</summary>
private static async Task Scenario2_OneOfManyAsync(ArxPgDbService service)
{
Step("2. One of many");
var account = new ArxEntity("account");
account["name"] = "Margie's Travel";
account["account_number"] = "ACC-U401";
var id = await service.CreateAsync(account);
var real = new ArxEntity("account");
real.RecordId = id;
real["name"] = "Margie's Travel Agency";
var ghost = new ArxEntity("account");
ghost["id"] = 999_999_997L;
ghost["name"] = "Ghost";
try
{
await service.UpdateMultipleAsync(new[] { real, ghost });
}
catch (ArxException error) when (error.Code == ArxErrorCode.RecordNotFound)
{
Show($"{error.Message}");
}
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* SELECT name
* FROM account
* WHERE account_number = 'ACC-U401';
* -- Expect: 1 row, Margie's Travel: the real account wasn't renamed either.
* ===========================================================
*/
}
}
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. One record
ARX2002 RecordNotFound: Update of 'account': no row matched the id (column id). Nothing was changed.
> 2. One of many
ARX2002 RecordNotFound: UpdateMultiple on 'account': 1 of 2 entities matched no row. Nothing was changed.