SQL Server · DeleteMultiple
Remove the contacts a user selected
Removing the contacts a user ticked, in two scenarios: a list screen that has their ids, and an unsubscribe file that has only email addresses (the contact table's declared key).
Set up for this page
The scenarios build on the sample application: SampleContext.cs (the dbContext every sample is given); SampleOutput.cs (Step and Show, which print); SampleContext.Application.cs (dbContext.Service, the application's ARX service); SampleCatalog.cs (the tables' ids, keys, lookups and display names).
Before scenario 1 the sample runs this, so the service and the rows the scenarios use are there:
var contacts = new List<ArxEntity>();
foreach (var (first, last) in new[] { ("Ines", "Moreau"), ("Kenji", "Sato"), ("Lena", "Fischer"), ("Marco", "Bianchi"), ("Nadia", "Rahman") })
{
var contact = new ArxEntity("contact");
contact["first_name"] = first;
contact["last_name"] = last;
contact["email"] = $"{first.ToLowerInvariant()}.{last.ToLowerInvariant()}@example.com";
contacts.Add(contact);
}
var ids = await service.CreateMultipleAsync(contacts);1 The ticked rows of a list
The list screen sends the ids of the rows the user ticked.
Already in scope: service (ArxMsSqlDbService), selected (IReadOnlyList<ArxRecordId>)
int deleted = await service.DeleteMultipleAsync("contact", selected);
Console.WriteLine($"{deleted} of {selected.Count} selected contacts removed");Check it in the database
Run it in any SQL tool connected to the database, after the code has run.
SELECT count(*)
FROM contact
WHERE email IN ('ines.moreau@example.com', 'kenji.sato@example.com', 'lena.fischer@example.com');Expect: 0.
2 An unsubscribe file of emails
An unsubscribe file has only emails: one entity per address, found by the declared key.
Already in scope: service (ArxMsSqlDbService)
var file = new[] { "marco.bianchi@example.com", "nadia.rahman@example.com", "nobody@example.com" };
var requests = file.Select(email =>
{
var request = new ArxEntity("contact");
request["email"] = email;
return request;
}).ToList();
// An address with no contact isn't an error: the count says how many were really there.
int deleted = await service.DeleteMultipleAsync(requests, new ArxDeleteOptions { Match = ArxMatch.Key("email") });
Console.WriteLine($"{deleted} of {file.Length} addresses removed");Check it in the database
Run it in any SQL tool connected to the database, after the code has run.
SELECT count(*)
FROM contact
WHERE email IN ('marco.bianchi@example.com', 'nadia.rahman@example.com');Expect: 0.
Good to know
Both are one call, all or nothing: either every matching contact goes or, when the database refuses one (a reference to it, for example), none does.
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.SQL --version 1.0.0-rc.1 - Database: a SQL Server 2022 (tested with 16.0.4225.2) database with the sample schema.
- Configuration: set
ARX_SAMPLES_SQLSERVERto its connection string. Nothing is hard-coded. - Source code: add the files of the sample application this sample uses (
SampleContext.cs,SampleOutput.cs,SampleContext.Application.cs,SampleCatalog.cs), then replaceProgram.csand add the other file 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.MSSQL;
using ArxSamples.MSSQL.Operations.DeleteMultiple.RealCases;
// The connection string comes from the environment, never from the code (see "Configure the connection").
var connectionString = Environment.GetEnvironmentVariable("ARX_SAMPLES_SQLSERVER")
?? throw new InvalidOperationException("Set the ARX_SAMPLES_SQLSERVER environment variable to your SQL Server connection string.");
await new RealCase1_RemoveSelectedContacts().RunAsync(new SampleContext(connectionString));
The sample, as it is in the repository.
using ARX.SDK.Services;
using static ArxSamples.MSSQL.SampleOutput;
namespace ArxSamples.MSSQL.Operations.DeleteMultiple.RealCases;
/// <summary>
/// Removing the contacts a user ticked, in two scenarios: a list screen that has their ids, and an unsubscribe file
/// that has only email addresses (the contact table's declared key).
/// </summary>
/// <remarks>
/// <para>Both are one call, all or nothing: either every matching contact goes or, when the database refuses one (a
/// reference to it, for example), none does.</para>
/// </remarks>
public sealed class RealCase1_RemoveSelectedContacts : ISample
{
public string Name => "delete-multiple-real-1-remove-selected-contacts";
public string Title => "Remove the contacts a user selected";
public async Task RunAsync(SampleContext dbContext)
{
var contacts = new List<ArxEntity>();
foreach (var (first, last) in new[] { ("Ines", "Moreau"), ("Kenji", "Sato"), ("Lena", "Fischer"), ("Marco", "Bianchi"), ("Nadia", "Rahman") })
{
var contact = new ArxEntity("contact");
contact["first_name"] = first;
contact["last_name"] = last;
contact["email"] = $"{first.ToLowerInvariant()}.{last.ToLowerInvariant()}@example.com";
contacts.Add(contact);
}
var ids = await dbContext.Service.CreateMultipleAsync(contacts);
await Scenario1_TheTickedRowsOfAListAsync(dbContext, new[] { ids[0], ids[1], ids[2] });
await Scenario2_AnUnsubscribeFileOfEmailsAsync(dbContext);
}
/// <summary>1. The list screen sends the ids of the rows the user ticked.</summary>
private static async Task Scenario1_TheTickedRowsOfAListAsync(SampleContext dbContext, IReadOnlyList<ArxRecordId> selected)
{
Step("1. The ticked rows of a list");
int deleted = await dbContext.Service.DeleteMultipleAsync("contact", selected);
Show($"{deleted} of {selected.Count} selected contacts removed");
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* SELECT count(*)
* FROM contact
* WHERE email IN ('ines.moreau@example.com', 'kenji.sato@example.com', 'lena.fischer@example.com');
* -- Expect: 0.
* ===========================================================
*/
}
/// <summary>2. An unsubscribe file has only emails: one entity per address, found by the declared key.</summary>
private static async Task Scenario2_AnUnsubscribeFileOfEmailsAsync(SampleContext dbContext)
{
Step("2. An unsubscribe file of emails");
var file = new[] { "marco.bianchi@example.com", "nadia.rahman@example.com", "nobody@example.com" };
var requests = file.Select(email =>
{
var request = new ArxEntity("contact");
request["email"] = email;
return request;
}).ToList();
// An address with no contact isn't an error: the count says how many were really there.
int deleted = await dbContext.Service.DeleteMultipleAsync(requests, new ArxDeleteOptions { Match = ArxMatch.Key("email") });
Show($"{deleted} of {file.Length} addresses removed");
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* SELECT count(*)
* FROM contact
* WHERE email IN ('marco.bianchi@example.com', 'nadia.rahman@example.com');
* -- Expect: 0.
* ===========================================================
*/
}
}
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. The ticked rows of a list
3 of 3 selected contacts removed
> 2. An unsubscribe file of emails
2 of 3 addresses removed