PostgreSQL · Update

Clear a value, keep the others

What an update writes, in three scenarios: an attribute set to null clears the column; an attribute you leave out keeps its value; ArxIgnore leaves out an attribute that is on the entity anyway. Each scenario has its own account.

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("account", ArxIdColumn.Generated<long>("id"))
    .Build());

1 Null clears

Set an attribute to null to clear the column.

Already in scope: service (ArxPgDbService)

C#
var id = await CreateAccountAsync(service, "ACC-U301");

var change = new ArxEntity("account");
change.RecordId = id;
change["website"] = null;

await service.UpdateAsync(change);

Console.WriteLine("website cleared");
Used above

Defined once in this sample.

private static async Task<ArxRecordId> CreateAccountAsync(ArxPgDbService service, string number)
{
    var account = new ArxEntity("account");
    account["name"] = "Proseware Labs";
    account["account_number"] = number;
    account["website"] = "https://proseware.example";
    account["employee_count"] = 12;
    return await service.CreateAsync(account);
}

Check it in the database

SQL

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

SELECT name, website, employee_count
FROM account
WHERE account_number = 'ACC-U301';

Expect: 1 row, Proseware Labs, website NULL, employee_count 12.

2 Left out keeps its value

An attribute you don't set isn't touched: this update changes the name only.

Already in scope: service (ArxPgDbService)

C#
var id = await CreateAccountAsync(service, "ACC-U302");

var change = new ArxEntity("account");
change.RecordId = id;
change["name"] = "Proseware Laboratories";

await service.UpdateAsync(change);

Console.WriteLine("name changed, website and employee_count kept");
Used above

Defined once in this sample.

private static async Task<ArxRecordId> CreateAccountAsync(ArxPgDbService service, string number)
{
    var account = new ArxEntity("account");
    account["name"] = "Proseware Labs";
    account["account_number"] = number;
    account["website"] = "https://proseware.example";
    account["employee_count"] = 12;
    return await service.CreateAsync(account);
}

Check it in the database

SQL

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

SELECT name, website, employee_count
FROM account
WHERE account_number = 'ACC-U302';

Expect: 1 row, Proseware Laboratories, https://proseware.example, employee_count 12.

3 ArxIgnore

An entity you reuse may hold attributes you don't want written: mark them ArxIgnore.

Already in scope: service (ArxPgDbService)

C#
var id = await CreateAccountAsync(service, "ACC-U303");

var change = new ArxEntity("account");
change.RecordId = id;
change["employee_count"] = 14;
change["name"] = new ArxIgnore();

await service.UpdateAsync(change);

Console.WriteLine("employee_count changed, name not written");
Used above

Defined once in this sample.

private static async Task<ArxRecordId> CreateAccountAsync(ArxPgDbService service, string number)
{
    var account = new ArxEntity("account");
    account["name"] = "Proseware Labs";
    account["account_number"] = number;
    account["website"] = "https://proseware.example";
    account["employee_count"] = 12;
    return await service.CreateAsync(account);
}

Check it in the database

SQL

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-U303';

Expect: 1 row, Proseware Labs, employee_count 14.

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

The sample, as it is in the repository.

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

using static ArxSamples.PostgreSql.SampleOutput;

namespace ArxSamples.PostgreSql.Operations.Update.Basics;

/// <summary>
/// What an update writes, in three scenarios: an attribute set to null clears the column; an attribute you leave out
/// keeps its value; <see cref="ArxIgnore"/> leaves out an attribute that is on the entity anyway. Each scenario has its
/// own account.
/// </summary>
public sealed class Basic2_ClearAValue : ISample
{
    public string Name => "update-basics-2-clear-a-value";

    public string Title => "Clear a value, keep the others";

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

        await Scenario1_NullClearsAsync(service);

        await Scenario2_LeftOutKeepsItsValueAsync(service);

        await Scenario3_ArxIgnoreAsync(service);
    }

    private static async Task<ArxRecordId> CreateAccountAsync(ArxPgDbService service, string number)
    {
        var account = new ArxEntity("account");
        account["name"] = "Proseware Labs";
        account["account_number"] = number;
        account["website"] = "https://proseware.example";
        account["employee_count"] = 12;
        return await service.CreateAsync(account);
    }

    /// <summary>1. Set an attribute to null to clear the column.</summary>
    private static async Task Scenario1_NullClearsAsync(ArxPgDbService service)
    {
        Step("1. Null clears");

        var id = await CreateAccountAsync(service, "ACC-U301");

        var change = new ArxEntity("account");
        change.RecordId = id;
        change["website"] = null;

        await service.UpdateAsync(change);

        Show("website cleared");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT name, website, employee_count
         * FROM account
         * WHERE account_number = 'ACC-U301';
         * -- Expect: 1 row, Proseware Labs, website NULL, employee_count 12.
         * ===========================================================
         */
    }

    /// <summary>2. An attribute you don't set isn't touched: this update changes the name only.</summary>
    private static async Task Scenario2_LeftOutKeepsItsValueAsync(ArxPgDbService service)
    {
        Step("2. Left out keeps its value");

        var id = await CreateAccountAsync(service, "ACC-U302");

        var change = new ArxEntity("account");
        change.RecordId = id;
        change["name"] = "Proseware Laboratories";

        await service.UpdateAsync(change);

        Show("name changed, website and employee_count kept");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT name, website, employee_count
         * FROM account
         * WHERE account_number = 'ACC-U302';
         * -- Expect: 1 row, Proseware Laboratories, https://proseware.example, employee_count 12.
         * ===========================================================
         */
    }

    /// <summary>3. An entity you reuse may hold attributes you don't want written: mark them ArxIgnore.</summary>
    private static async Task Scenario3_ArxIgnoreAsync(ArxPgDbService service)
    {
        Step("3. ArxIgnore");

        var id = await CreateAccountAsync(service, "ACC-U303");

        var change = new ArxEntity("account");
        change.RecordId = id;
        change["employee_count"] = 14;
        change["name"] = new ArxIgnore();

        await service.UpdateAsync(change);

        Show("employee_count changed, name not written");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT name, employee_count
         * FROM account
         * WHERE account_number = 'ACC-U303';
         * -- Expect: 1 row, Proseware Labs, employee_count 14.
         * ===========================================================
         */
    }
}
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. Null clears
      website cleared
  > 2. Left out keeps its value
      name changed, website and employee_count kept
  > 3. ArxIgnore
      employee_count changed, name not written