MySQL · UpdateMultiple

Update many records without a catalog

Many records in one call on a service created with only a connection string: the account table is read from the database once for the whole list, then every row is changed, all or nothing.

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 A value per row

One entity per record, by the ids CreateMultiple returned.

Already in scope: connectionString (string)

C#
var service = new ArxMySqlDbService(connectionString);

var accounts = new List<ArxEntity>();
for (var i = 1; i <= 3; i++)
{
    var account = new ArxEntity("account");
    account["name"] = $"No catalog {i}";
    account["account_number"] = $"ACC-N03{i}";
    account["employee_count"] = 10;
    accounts.Add(account);
}

var ids = await service.CreateMultipleAsync(accounts);

var changes = new List<ArxEntity>();
for (var i = 0; i < ids.Count; i++)
{
    var change = new ArxEntity("account");
    change.RecordId = ids[i];
    change["employee_count"] = 20 + i;
    changes.Add(change);
}

int changed = await service.UpdateMultipleAsync(changes);

Console.WriteLine($"{changed} accounts changed in one call");

Check it in the database

SQL

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

SELECT account_number, employee_count
FROM account
WHERE account_number IN ('ACC-N031', 'ACC-N032', 'ACC-N033')
ORDER BY account_number;

Expect: 3 rows, employee_count 20, 21, 22.

Good to know

The extra round trip is paid once per call, not once per row; still, a service with a catalog never pays it.

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

The sample, as it is in the repository.

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

using static ArxSamples.MySQL.SampleOutput;

namespace ArxSamples.MySQL.Operations.UpdateMultiple.Basics;

/// <summary>
/// Many records in one call on a service created with only a connection string: the account table is read from the
/// database once for the whole list, then every row is changed, all or nothing.
/// </summary>
/// <remarks>
/// <para>The extra round trip is paid once per call, not once per row; still, a service with a catalog never pays it.</para>
/// </remarks>
public sealed class Basic2_WithoutACatalog : ISample
{
    public string Name => "update-multiple-basics-2-without-a-catalog";

    public string Title => "Update many records without a catalog";

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

    /// <summary>1. One entity per record, by the ids CreateMultiple returned.</summary>
    private static async Task Scenario1_AValuePerRowAsync(string connectionString)
    {
        Step("1. A value per row");

        var service = new ArxMySqlDbService(connectionString);

        var accounts = new List<ArxEntity>();
        for (var i = 1; i <= 3; i++)
        {
            var account = new ArxEntity("account");
            account["name"] = $"No catalog {i}";
            account["account_number"] = $"ACC-N03{i}";
            account["employee_count"] = 10;
            accounts.Add(account);
        }

        var ids = await service.CreateMultipleAsync(accounts);

        var changes = new List<ArxEntity>();
        for (var i = 0; i < ids.Count; i++)
        {
            var change = new ArxEntity("account");
            change.RecordId = ids[i];
            change["employee_count"] = 20 + i;
            changes.Add(change);
        }

        int changed = await service.UpdateMultipleAsync(changes);

        Show($"{changed} accounts changed in one call");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT account_number, employee_count
         * FROM account
         * WHERE account_number IN ('ACC-N031', 'ACC-N032', 'ACC-N033')
         * ORDER BY account_number;
         * -- Expect: 3 rows, employee_count 20, 21, 22.
         * ===========================================================
         */
    }
}
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. A value per row
      3 accounts changed in one call