MySQL · DeleteMultiple
Delete many records in one call
Many records in one call, in two scenarios: by the ids CreateMultiple returned; and a list with an id that doesn't exist and one given twice, both counted honestly.
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:
var service = new ArxMySqlDbService(connectionString, ArxSchemaCatalog.Create()
.Table("account", ArxIdColumn.Generated<long>("id"))
.Build());1 By the ids Create returned
The usual way: the table and the ids. The call returns how many records went.
Already in scope: service (ArxMySqlDbService)
var ids = await CreateAccountsAsync(service, 1, 5);
int deleted = await service.DeleteMultipleAsync("account", ids);
Console.WriteLine($"{deleted} deleted");Defined once in this sample.
private static async Task<IReadOnlyList<ArxRecordId>> CreateAccountsAsync(ArxMySqlDbService service, int first, int count)
{
var accounts = Enumerable.Range(first, count).Select(i =>
{
var account = new ArxEntity("account");
account["name"] = $"Delete many {i}";
account["account_number"] = $"ACC-D2{i:00}";
return account;
}).ToList();
return await service.CreateMultipleAsync(accounts);
}Check it in the database
Run it in any SQL tool connected to the database, after the code has run.
SELECT count(*)
FROM account
WHERE account_number BETWEEN 'ACC-D201' AND 'ACC-D205';Expect: 0.
2 Missing and repeated ids
A missing id isn't an error, and an id given twice goes once: the count says what really happened.
Already in scope: service (ArxMySqlDbService)
var ids = (await CreateAccountsAsync(service, 11, 3)).Select(x => x.AsInt64()).ToList();
var list = new List<long> { ids[0], ids[1], ids[2], ids[0], 999_999_995 };
int deleted = await service.DeleteMultipleAsync("account", list);
Console.WriteLine($"asked for {list.Count}, {deleted} deleted");Defined once in this sample.
private static async Task<IReadOnlyList<ArxRecordId>> CreateAccountsAsync(ArxMySqlDbService service, int first, int count)
{
var accounts = Enumerable.Range(first, count).Select(i =>
{
var account = new ArxEntity("account");
account["name"] = $"Delete many {i}";
account["account_number"] = $"ACC-D2{i:00}";
return account;
}).ToList();
return await service.CreateMultipleAsync(accounts);
}Check it in the database
Run it in any SQL tool connected to the database, after the code has run.
SELECT count(*)
FROM account
WHERE account_number BETWEEN 'ACC-D211' AND 'ACC-D213';Expect: 0.
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
- .NET SDK: .NET SDK 10.0.100 or later 10.0.x (target
net10.0). - Create the project:
Terminal dotnet new console -n ArxSample -f net10.0 cd ArxSample - Install the packages:
Terminal dotnet add package ARX.SDK.MySQL --version 1.0.0-rc.1 - Database: a MySQL 8.4 (tested with 8.4.13) database with the sample schema.
- Configuration: set
ARX_SAMPLES_MYSQLto its connection string. Nothing is hard-coded. - Source code: replace
Program.csand add the 3 other files below, with the file names shown. - Run it:
Terminal dotnet run - Expected output: below.
The files
Runs the sample. Generated for this page; it reads the connection string from the environment.
using ArxSamples.MySQL;
using ArxSamples.MySQL.Operations.DeleteMultiple.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_DeleteManyRecords().RunAsync(new SampleContext(connectionString));
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.DeleteMultiple.Basics;
/// <summary>
/// Many records in one call, in two scenarios: by the ids CreateMultiple returned; and a list with an id that doesn't
/// exist and one given twice, both counted honestly.
/// </summary>
public sealed class Basic1_DeleteManyRecords : ISample
{
public string Name => "delete-multiple-basics-1-delete-many-records";
public string Title => "Delete many records in one call";
public async Task RunAsync(SampleContext dbContext)
{
var service = new ArxMySqlDbService(dbContext.ConnectionString, ArxSchemaCatalog.Create()
.Table("account", ArxIdColumn.Generated<long>("id"))
.Build());
await Scenario1_ByTheIdsCreateReturnedAsync(service);
await Scenario2_MissingAndRepeatedIdsAsync(service);
}
private static async Task<IReadOnlyList<ArxRecordId>> CreateAccountsAsync(ArxMySqlDbService service, int first, int count)
{
var accounts = Enumerable.Range(first, count).Select(i =>
{
var account = new ArxEntity("account");
account["name"] = $"Delete many {i}";
account["account_number"] = $"ACC-D2{i:00}";
return account;
}).ToList();
return await service.CreateMultipleAsync(accounts);
}
/// <summary>1. The usual way: the table and the ids. The call returns how many records went.</summary>
private static async Task Scenario1_ByTheIdsCreateReturnedAsync(ArxMySqlDbService service)
{
Step("1. By the ids Create returned");
var ids = await CreateAccountsAsync(service, 1, 5);
int deleted = await service.DeleteMultipleAsync("account", ids);
Show($"{deleted} deleted");
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* SELECT count(*)
* FROM account
* WHERE account_number BETWEEN 'ACC-D201' AND 'ACC-D205';
* -- Expect: 0.
* ===========================================================
*/
}
/// <summary>2. A missing id isn't an error, and an id given twice goes once: the count says what really happened.</summary>
private static async Task Scenario2_MissingAndRepeatedIdsAsync(ArxMySqlDbService service)
{
Step("2. Missing and repeated ids");
var ids = (await CreateAccountsAsync(service, 11, 3)).Select(x => x.AsInt64()).ToList();
var list = new List<long> { ids[0], ids[1], ids[2], ids[0], 999_999_995 };
int deleted = await service.DeleteMultipleAsync("account", list);
Show($"asked for {list.Count}, {deleted} deleted");
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* SELECT count(*)
* FROM account
* WHERE account_number BETWEEN 'ACC-D211' AND 'ACC-D213';
* -- Expect: 0.
* ===========================================================
*/
}
}
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 -- <name></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; }
}
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.
> 1. By the ids Create returned
5 deleted
> 2. Missing and repeated ids
asked for 5, 3 deleted