PostgreSQL · Delete

Delete one record

The smallest delete: one record, in three scenarios. The usual way first (the id CreateAsync returned), then a text id, then the entity itself.

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 and the id. True when a record was deleted.

Already in scope: connectionString (string)

C#
var service = Service(connectionString);

var account = new ArxEntity("account");
account["name"] = "Temporary account";
account["account_number"] = "ACC-D101";
ArxRecordId id = await service.CreateAsync(account);

bool deleted = await service.DeleteAsync("account", id);

Console.WriteLine($"deleted = {deleted}");
Used above

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

SQL

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

SELECT count(*)
FROM account
WHERE account_number = 'ACC-D101';

Expect: 0.

2 A text id

A text id: delete a country by its code.

Already in scope: connectionString (string)

C#
var service = Service(connectionString);

var finland = new ArxEntity("country");
finland["code"] = "FI";
finland["name"] = "Finland";
await service.CreateAsync(finland);

bool deleted = await service.DeleteAsync("country", "FI");

Console.WriteLine($"country FI deleted = {deleted}");
Used above

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

SQL

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

SELECT count(*)
FROM country
WHERE code = 'FI';

Expect: 0.

3 The entity itself

The entity itself: an entity you created (or read) carries its id, so you can pass it back to delete it. The row is found by the table's declared id only ("id" in the schema above), never by the other attributes.

Already in scope: connectionString (string)

C#
var service = Service(connectionString);

var account = new ArxEntity("account");
account["name"] = "Another temporary account";
account["account_number"] = "ACC-D103";
await service.CreateAsync(account); // sets account.RecordId to the new row's id

// Finds the row by account.RecordId: DELETE FROM account WHERE id = <that id>.
// "name" and "account_number" are not part of the match and are ignored: no other account is deleted because
// it has the same name or number, and account_number is not a key (it isn't declared as one in the schema).
// To delete by account_number instead, ask for it: new ArxDeleteOptions { Match = ArxMatch.Columns("account_number") }
// (see Basic3_HowToFindTheRows on this page).
int deleted = await service.DeleteAsync(account);

Console.WriteLine($"{deleted} row deleted");
Used above

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

SQL

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

SELECT count(*)
FROM account
WHERE account_number = 'ACC-D103';

Expect: 0 (the account created above is gone). account_number is used here only to find the row by hand, since you don't know its generated id; the delete itself matched on id.

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.Delete.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_DeleteOneRecord().RunAsync(new SampleContext(connectionString));
Basic1_DeleteOneRecord.cs

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.Delete.Basics;

/// <summary>
/// The smallest delete: one record, in three scenarios. The usual way first (the id CreateAsync returned), then a text
/// id, then the entity itself.
/// </summary>
public sealed class Basic1_DeleteOneRecord : ISample
{
    public string Name => "delete-basics-1-delete-one-record";

    public string Title => "Delete one record";

    public async Task RunAsync(SampleContext dbContext)
    {
        await Scenario1_ByTheIdCreateReturnedAsync(dbContext.ConnectionString);

        await Scenario2_ATextIdAsync(dbContext.ConnectionString);

        await Scenario3_TheEntityItselfAsync(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 and the id. True when a record was deleted.</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"] = "Temporary account";
        account["account_number"] = "ACC-D101";
        ArxRecordId id = await service.CreateAsync(account);

        bool deleted = await service.DeleteAsync("account", id);

        Show($"deleted = {deleted}");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT count(*)
         * FROM account
         * WHERE account_number = 'ACC-D101';
         * -- Expect: 0.
         * ===========================================================
         */
    }

    /// <summary>2. A text id: delete a country by its code.</summary>
    private static async Task Scenario2_ATextIdAsync(string connectionString)
    {
        Step("2. A text id");

        var service = Service(connectionString);

        var finland = new ArxEntity("country");
        finland["code"] = "FI";
        finland["name"] = "Finland";
        await service.CreateAsync(finland);

        bool deleted = await service.DeleteAsync("country", "FI");

        Show($"country FI deleted = {deleted}");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT count(*)
         * FROM country
         * WHERE code = 'FI';
         * -- Expect: 0.
         * ===========================================================
         */
    }

    /// <summary>
    /// 3. The entity itself: an entity you created (or read) carries its id, so you can pass it back to delete it.
    /// The row is found by the table's declared id only ("id" in the schema above), never by the other attributes.
    /// </summary>
    private static async Task Scenario3_TheEntityItselfAsync(string connectionString)
    {
        Step("3. The entity itself");

        var service = Service(connectionString);

        var account = new ArxEntity("account");
        account["name"] = "Another temporary account";
        account["account_number"] = "ACC-D103";
        await service.CreateAsync(account); // sets account.RecordId to the new row's id

        // Finds the row by account.RecordId: DELETE FROM account WHERE id = <that id>.
        // "name" and "account_number" are not part of the match and are ignored: no other account is deleted because
        // it has the same name or number, and account_number is not a key (it isn't declared as one in the schema).
        // To delete by account_number instead, ask for it: new ArxDeleteOptions { Match = ArxMatch.Columns("account_number") }
        // (see Basic3_HowToFindTheRows on this page).
        int deleted = await service.DeleteAsync(account);

        Show($"{deleted} row deleted");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT count(*)
         * FROM account
         * WHERE account_number = 'ACC-D103';
         * -- Expect: 0 (the account created above is gone).
         * -- account_number is used here only to find the row by hand, since you don't know its generated id;
         * -- the delete itself matched on id.
         * ===========================================================
         */
    }
}
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 the id Create returned
      deleted = True
  > 2. A text id
      country FI deleted = True
  > 3. The entity itself
      1 row deleted