MySQL · Update

Find rows by id, by key or by columns

How an update finds its rows (ArxMatch), in four scenarios: by id (the default), by a declared key, by any columns (which may match many rows), and strict: exactly one row, or nothing changes.

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

1 By id

The default: by the table's id. The other ways below are for when you don't have it.

Already in scope: service (ArxMySqlDbService)

C#
var account = new ArxEntity("account");
account["name"] = "Lucerne Publishing";
account["account_number"] = "ACC-U501";
var id = await service.CreateAsync(account);

var change = new ArxEntity("account");
change.RecordId = id;
change["employee_count"] = 30;
await service.UpdateAsync(change);

Console.WriteLine("ACC-U501 updated by its id");

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

Expect: 1 row, employee_count 30.

2 By a key

By a declared key: you know the account number, not the id.

Already in scope: service (ArxMySqlDbService)

C#
var account = new ArxEntity("account");
account["name"] = "Coho Winery";
account["account_number"] = "ACC-U502";
await service.CreateAsync(account);

var change = new ArxEntity("account");
change["account_number"] = "ACC-U502";
change["employee_count"] = 18;

await service.UpdateAsync(change, new ArxUpdateOptions { Match = ArxMatch.Key("account_number") });

Console.WriteLine("ACC-U502 updated by its account number");

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

Expect: 1 row, Coho Winery, employee_count 18.

3 By columns

By any columns: every contact from one import is marked "do not email". Many rows change.

Already in scope: service (ArxMySqlDbService)

C#
var contacts = Enumerable.Range(1, 4).Select(i =>
{
    var contact = new ArxEntity("contact");
    contact["first_name"] = "Imported";
    contact["last_name"] = $"Contact {i}";
    contact["email"] = $"import-u5-{i}@example.com";
    contact["lead_source"] = "Expo U5";
    return contact;
}).ToList();
await service.CreateMultipleAsync(contacts);

var change = new ArxEntity("contact");
change["lead_source"] = "Expo U5";
change["do_not_email"] = true;

int changed = await service.UpdateAsync(change, new ArxUpdateOptions { Match = ArxMatch.Columns("lead_source") });

Console.WriteLine($"{changed} contacts from Expo U5 marked do not email");

Check it in the database

SQL

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

SELECT count(*)
FROM contact
WHERE lead_source = 'Expo U5' AND do_not_email;

Expect: 4.

4 Strict

Strict: RequireSingleRow refuses an update that would change more than one row, and changes nothing.

Already in scope: service (ArxMySqlDbService)

C#
var change = new ArxEntity("contact");
change["lead_source"] = "Expo U5";
change["job_title"] = "Buyer";

try
{
    await service.UpdateAsync(change, new ArxUpdateOptions { Match = ArxMatch.Columns("lead_source"), RequireSingleRow = true });
}
catch (ArxException error) when (error.Code == ArxErrorCode.MultipleRecordsMatched)
{
    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 contact
WHERE lead_source = 'Expo U5' AND job_title = 'Buyer';

Expect: 0: four contacts matched, so none was changed.

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 Basic4_HowToFindTheRows().RunAsync(new SampleContext(connectionString));
Basic4_HowToFindTheRows.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>
/// How an update finds its rows (ArxMatch), in four scenarios: by id (the default), by a declared key, by any columns
/// (which may match many rows), and strict: exactly one row, or nothing changes.
/// </summary>
public sealed class Basic4_HowToFindTheRows : ISample
{
    public string Name => "update-basics-4-how-to-find-the-rows";

    public string Title => "Find rows by id, by key or by columns";

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

        await Scenario1_ByIdAsync(service);

        await Scenario2_ByADeclaredKeyAsync(service);

        await Scenario3_ByAnyColumnsAsync(service);

        await Scenario4_StrictExactlyOneRowAsync(service);
    }

    /// <summary>1. The default: by the table's id. The other ways below are for when you don't have it.</summary>
    private static async Task Scenario1_ByIdAsync(ArxMySqlDbService service)
    {
        Step("1. By id");

        var account = new ArxEntity("account");
        account["name"] = "Lucerne Publishing";
        account["account_number"] = "ACC-U501";
        var id = await service.CreateAsync(account);

        var change = new ArxEntity("account");
        change.RecordId = id;
        change["employee_count"] = 30;
        await service.UpdateAsync(change);

        Show("ACC-U501 updated by its id");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT name, employee_count
         * FROM account
         * WHERE account_number = 'ACC-U501';
         * -- Expect: 1 row, employee_count 30.
         * ===========================================================
         */
    }

    /// <summary>2. By a declared key: you know the account number, not the id.</summary>
    private static async Task Scenario2_ByADeclaredKeyAsync(ArxMySqlDbService service)
    {
        Step("2. By a key");

        var account = new ArxEntity("account");
        account["name"] = "Coho Winery";
        account["account_number"] = "ACC-U502";
        await service.CreateAsync(account);

        var change = new ArxEntity("account");
        change["account_number"] = "ACC-U502";
        change["employee_count"] = 18;

        await service.UpdateAsync(change, new ArxUpdateOptions { Match = ArxMatch.Key("account_number") });

        Show("ACC-U502 updated by its account number");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT name, employee_count
         * FROM account
         * WHERE account_number = 'ACC-U502';
         * -- Expect: 1 row, Coho Winery, employee_count 18.
         * ===========================================================
         */
    }

    /// <summary>3. By any columns: every contact from one import is marked "do not email". Many rows change.</summary>
    private static async Task Scenario3_ByAnyColumnsAsync(ArxMySqlDbService service)
    {
        Step("3. By columns");

        var contacts = Enumerable.Range(1, 4).Select(i =>
        {
            var contact = new ArxEntity("contact");
            contact["first_name"] = "Imported";
            contact["last_name"] = $"Contact {i}";
            contact["email"] = $"import-u5-{i}@example.com";
            contact["lead_source"] = "Expo U5";
            return contact;
        }).ToList();
        await service.CreateMultipleAsync(contacts);

        var change = new ArxEntity("contact");
        change["lead_source"] = "Expo U5";
        change["do_not_email"] = true;

        int changed = await service.UpdateAsync(change, new ArxUpdateOptions { Match = ArxMatch.Columns("lead_source") });

        Show($"{changed} contacts from Expo U5 marked do not email");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT count(*)
         * FROM contact
         * WHERE lead_source = 'Expo U5' AND do_not_email;
         * -- Expect: 4.
         * ===========================================================
         */
    }

    /// <summary>4. Strict: RequireSingleRow refuses an update that would change more than one row, and changes nothing.</summary>
    private static async Task Scenario4_StrictExactlyOneRowAsync(ArxMySqlDbService service)
    {
        Step("4. Strict");

        var change = new ArxEntity("contact");
        change["lead_source"] = "Expo U5";
        change["job_title"] = "Buyer";

        try
        {
            await service.UpdateAsync(change, new ArxUpdateOptions { Match = ArxMatch.Columns("lead_source"), RequireSingleRow = true });
        }
        catch (ArxException error) when (error.Code == ArxErrorCode.MultipleRecordsMatched)
        {
            Show($"{error.Message}");
        }

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT count(*)
         * FROM contact
         * WHERE lead_source = 'Expo U5' AND job_title = 'Buyer';
         * -- Expect: 0: four contacts matched, so none was changed.
         * ===========================================================
         */
    }
}
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. By id
      ACC-U501 updated by its id
  > 2. By a key
      ACC-U502 updated by its account number
  > 3. By columns
      4 contacts from Expo U5 marked do not email
  > 4. Strict
      ARX2003 MultipleRecordsMatched: Update on 'contact': 1 entities matched 4 rows, but RequireSingleRow needs exactly one each. Nothing was changed.