MySQL · 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:

Set up
var service = new ArxMySqlDbService(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 (ArxMySqlDbService)

C#
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

SQL

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 (ArxMySqlDbService)

C#
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

SQL

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

  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.MySQL --version 1.0.0-rc.1
  4. Database: a MySQL 8.4 (tested with 8.4.13) database with the sample schema.
  5. Configuration: set ARX_SAMPLES_MYSQL 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.MySQL;
using ArxSamples.MySQL.Operations.Update.Basics;

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

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

The sample, as it is in the repository.

using ARX.SDK;
using ARX.SDK.MySQL.Services;
using ARX.SDK.Services;

using static ArxSamples.MySQL.SampleOutput;

namespace ArxSamples.MySQL.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 ArxMySqlDbService(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(ArxMySqlDbService 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(ArxMySqlDbService 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.
         * ===========================================================
         */
    }
}
SampleContext.cs

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

namespace ArxSamples.MySQL;

/// <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 MySqlConnector 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.MySQL;

/// <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. 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.