MySQL · Update

Update one record

The smallest update: change one record, in four scenarios. Read them in order: the usual way first (the id that CreateAsync returned), then the other way (the id as an attribute), then a text id, then a table with no id column, whose record is found by its compound key.

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: keep the id CreateAsync returned, and give it to the entity you update.

Already in scope: connectionString (string)

C#
var schema = ArxSchemaCatalog.Create()
    .Table("account", ArxIdColumn.Generated<long>("id"))
    .Build();

var service = new ArxMySqlDbService(connectionString, schema);

var account = new ArxEntity("account");
account["name"] = "Fabrikam Outdoors";
account["account_number"] = "ACC-U101";
account["employee_count"] = 40;
ArxRecordId id = await service.CreateAsync(account);

// Only the attributes you set are written: the name and account number stay as they are.
var change = new ArxEntity("account");
change.RecordId = id;
change["employee_count"] = 55;
change["website"] = "https://fabrikam.example";

int changed = await service.UpdateAsync(change);

Console.WriteLine($"account {id.AsInt64()}, {changed} row changed");

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, website
FROM account
WHERE account_number = 'ACC-U101';

Expect: 1 row, Fabrikam Outdoors, employee_count 55, website https://fabrikam.example.

2 By the id attribute

The other way: the id as an attribute, for example a value that came from a form or an API.

Already in scope: connectionString (string)

C#
var schema = ArxSchemaCatalog.Create()
    .Table("account", ArxIdColumn.Generated<long>("id"))
    .Build();

var service = new ArxMySqlDbService(connectionString, schema);

var account = new ArxEntity("account");
account["name"] = "Wide World Importers";
account["account_number"] = "ACC-U102";
long accountId = (await service.CreateAsync(account)).AsInt64();

// The id attribute finds the row; it is never written, because it is the match.
var change = new ArxEntity("account");
change["id"] = accountId;
change["name"] = "Wide World Importers Ltd.";

await service.UpdateAsync(change);

Console.WriteLine($"account {accountId} renamed");

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

Expect: 1 row, Wide World Importers Ltd.

3 A text id

A text id: a country, found by its ISO code.

Already in scope: connectionString (string)

C#
var schema = ArxSchemaCatalog.Create()
    .Table("country", ArxIdColumn.Supplied<string>("code"))
    .Build();

var service = new ArxMySqlDbService(connectionString, schema);

var sweden = new ArxEntity("country");
sweden["code"] = "SE";
sweden["name"] = "Swden";
await service.CreateAsync(sweden);

// Fix the typo: the code is the id, the name is written.
var fix = new ArxEntity("country");
fix["code"] = "SE";
fix["name"] = "Sweden";
await service.UpdateAsync(fix);

Console.WriteLine("country SE renamed to Sweden");

Check it in the database

SQL

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

SELECT code, name
FROM country
WHERE code = 'SE';

Expect: 1 row, Sweden.

4 By a compound key

A table with no id column: a price is found by its region and SKU, the compound key.

Already in scope: connectionString (string)

C#
var schema = ArxSchemaCatalog.Create()
    .Table("country", ArxIdColumn.Supplied<string>("code"))
    .Table("price_list", ArxIdColumn.NoIdColumn).Key("price_list", "region", "sku")
    .Build();

var service = new ArxMySqlDbService(connectionString, schema);

var denmark = new ArxEntity("country");
denmark["code"] = "DK";
denmark["name"] = "Denmark";
await service.CreateAsync(denmark);

var price = new ArxEntity("price_list");
price["region"] = "DK";
price["sku"] = "SKU-U401";
price["unit_price"] = 12.00m;
price["valid_from"] = new DateOnly(2026, 1, 1);
await service.CreateAsync(price);

// There is no id, so say how to find the row: by the declared key.
var newPrice = new ArxEntity("price_list");
newPrice["region"] = "DK";
newPrice["sku"] = "SKU-U401";
newPrice["unit_price"] = 13.50m;

await service.UpdateAsync(newPrice, new ArxUpdateOptions { Match = ArxMatch.Key("region", "sku") });

Console.WriteLine("price DK / SKU-U401 is now 13.50");

Check it in the database

SQL

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

SELECT region, sku, unit_price, valid_from
FROM price_list
WHERE region = 'DK' AND sku = 'SKU-U401';

Expect: 1 row, unit_price 13.50, valid_from 2026-01-01 (not written, so unchanged).

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 Basic1_UpdateOneRecord().RunAsync(new SampleContext(connectionString));
Basic1_UpdateOneRecord.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.Update.Basics;

/// <summary>
/// The smallest update: change one record, in four scenarios. Read them in order: the usual way first (the id that
/// CreateAsync returned), then the other way (the id as an attribute), then a text id, then a table with no id column,
/// whose record is found by its compound key.
/// </summary>
public sealed class Basic1_UpdateOneRecord : ISample
{
    public string Name => "update-basics-1-update-one-record";

    public string Title => "Update one record";

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

        await Scenario2_ByTheIdAttributeAsync(dbContext.ConnectionString);

        await Scenario3_ATextIdAsync(dbContext.ConnectionString);

        await Scenario4_NoIdColumn_ByItsCompoundKeyAsync(dbContext.ConnectionString);
    }

    /// <summary>1. The usual way: keep the id CreateAsync returned, and give it to the entity you update.</summary>
    private static async Task Scenario1_ByTheIdCreateReturnedAsync(string connectionString)
    {
        Step("1. By the id Create returned");

        var schema = ArxSchemaCatalog.Create()
            .Table("account", ArxIdColumn.Generated<long>("id"))
            .Build();

        var service = new ArxMySqlDbService(connectionString, schema);

        var account = new ArxEntity("account");
        account["name"] = "Fabrikam Outdoors";
        account["account_number"] = "ACC-U101";
        account["employee_count"] = 40;
        ArxRecordId id = await service.CreateAsync(account);

        // Only the attributes you set are written: the name and account number stay as they are.
        var change = new ArxEntity("account");
        change.RecordId = id;
        change["employee_count"] = 55;
        change["website"] = "https://fabrikam.example";

        int changed = await service.UpdateAsync(change);

        Show($"account {id.AsInt64()}, {changed} row changed");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT name, employee_count, website
         * FROM account
         * WHERE account_number = 'ACC-U101';
         * -- Expect: 1 row, Fabrikam Outdoors, employee_count 55, website https://fabrikam.example.
         * ===========================================================
         */
    }

    /// <summary>2. The other way: the id as an attribute, for example a value that came from a form or an API.</summary>
    private static async Task Scenario2_ByTheIdAttributeAsync(string connectionString)
    {
        Step("2. By the id attribute");

        var schema = ArxSchemaCatalog.Create()
            .Table("account", ArxIdColumn.Generated<long>("id"))
            .Build();

        var service = new ArxMySqlDbService(connectionString, schema);

        var account = new ArxEntity("account");
        account["name"] = "Wide World Importers";
        account["account_number"] = "ACC-U102";
        long accountId = (await service.CreateAsync(account)).AsInt64();

        // The id attribute finds the row; it is never written, because it is the match.
        var change = new ArxEntity("account");
        change["id"] = accountId;
        change["name"] = "Wide World Importers Ltd.";

        await service.UpdateAsync(change);

        Show($"account {accountId} renamed");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT name
         * FROM account
         * WHERE account_number = 'ACC-U102';
         * -- Expect: 1 row, Wide World Importers Ltd.
         * ===========================================================
         */
    }

    /// <summary>3. A text id: a country, found by its ISO code.</summary>
    private static async Task Scenario3_ATextIdAsync(string connectionString)
    {
        Step("3. A text id");

        var schema = ArxSchemaCatalog.Create()
            .Table("country", ArxIdColumn.Supplied<string>("code"))
            .Build();

        var service = new ArxMySqlDbService(connectionString, schema);

        var sweden = new ArxEntity("country");
        sweden["code"] = "SE";
        sweden["name"] = "Swden";
        await service.CreateAsync(sweden);

        // Fix the typo: the code is the id, the name is written.
        var fix = new ArxEntity("country");
        fix["code"] = "SE";
        fix["name"] = "Sweden";
        await service.UpdateAsync(fix);

        Show("country SE renamed to Sweden");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT code, name
         * FROM country
         * WHERE code = 'SE';
         * -- Expect: 1 row, Sweden.
         * ===========================================================
         */
    }

    /// <summary>4. A table with no id column: a price is found by its region and SKU, the compound key.</summary>
    private static async Task Scenario4_NoIdColumn_ByItsCompoundKeyAsync(string connectionString)
    {
        Step("4. By a compound key");

        var schema = ArxSchemaCatalog.Create()
            .Table("country", ArxIdColumn.Supplied<string>("code"))
            .Table("price_list", ArxIdColumn.NoIdColumn).Key("price_list", "region", "sku")
            .Build();

        var service = new ArxMySqlDbService(connectionString, schema);

        var denmark = new ArxEntity("country");
        denmark["code"] = "DK";
        denmark["name"] = "Denmark";
        await service.CreateAsync(denmark);

        var price = new ArxEntity("price_list");
        price["region"] = "DK";
        price["sku"] = "SKU-U401";
        price["unit_price"] = 12.00m;
        price["valid_from"] = new DateOnly(2026, 1, 1);
        await service.CreateAsync(price);

        // There is no id, so say how to find the row: by the declared key.
        var newPrice = new ArxEntity("price_list");
        newPrice["region"] = "DK";
        newPrice["sku"] = "SKU-U401";
        newPrice["unit_price"] = 13.50m;

        await service.UpdateAsync(newPrice, new ArxUpdateOptions { Match = ArxMatch.Key("region", "sku") });

        Show("price DK / SKU-U401 is now 13.50");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT region, sku, unit_price, valid_from
         * FROM price_list
         * WHERE region = 'DK' AND sku = 'SKU-U401';
         * -- Expect: 1 row, unit_price 13.50, valid_from 2026-01-01 (not written, so unchanged).
         * ===========================================================
         */
    }
}
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 the id Create returned
      account 1, 1 row changed
  > 2. By the id attribute
      account 2 renamed
  > 3. A text id
      country SE renamed to Sweden
  > 4. By a compound key
      price DK / SKU-U401 is now 13.50