SQL Server · CreateMultiple
Create many records without reading their ids
Many records created when the program doesn't need their ids: ReturnIds = false reads none back, and SQL Server loads a group of 1,000 rows or more of one shape with SqlBulkCopy, constraints and triggers checked. Still 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 load without ids
A thousand accounts in one call; no id comes back.
Already in scope: connectionString (string)
var service = new ArxMsSqlDbService(connectionString, ArxSchemaCatalog.Create()
.Table("account", ArxIdColumn.Generated<long>("id"))
.Build());
var accounts = new List<ArxEntity>();
for (var i = 1; i <= 1000; i++)
{
var account = new ArxEntity("account");
account["name"] = $"Bulk account {i}";
account["account_number"] = $"ACC-F3{i:0000}";
account["employee_count"] = i % 50;
accounts.Add(account);
}
var ids = await service.CreateMultipleAsync(accounts, new ArxCreateMultipleOptions { ReturnIds = false });
Console.WriteLine($"{ids.Count} accounts created; ids returned: {ids.Count(x => x.HasValue)}");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 LIKE 'ACC-F3%';Expect: 1000.
Good to know
The call returns one ArxRecordId.None per entity, so code that switches between the two forms keeps its type.
Needs ARX.SDK 0.1.0-preview.5 or later.
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: 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.MSSQL;
using ArxSamples.MSSQL.Operations.CreateMultiple.Basics;
// 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 Basic3_WithoutIds().RunAsync(new SampleContext(connectionString));
The sample, as it is in the repository.
using ARX.SDK;
using ARX.SDK.SQL.Services;
using ARX.SDK.Services;
using static ArxSamples.MSSQL.SampleOutput;
namespace ArxSamples.MSSQL.Operations.CreateMultiple.Basics;
/// <summary>
/// Many records created when the program doesn't need their ids: ReturnIds = false reads none back, and SQL Server loads a group of 1,000 rows or
/// more of one shape with SqlBulkCopy, constraints and triggers checked. Still all
/// or nothing.
/// </summary>
/// <remarks>
/// <para>The call returns one ArxRecordId.None per entity, so code that switches between the two forms keeps its type.</para>
/// <para>Needs ARX.SDK 0.1.0-preview.5 or later.</para>
/// </remarks>
public sealed class Basic3_WithoutIds : ISample
{
public string Name => "create-multiple-basics-3-without-ids";
public string Title => "Create many records without reading their ids";
public async Task RunAsync(SampleContext dbContext)
{
await Scenario1_ALoadWithoutIdsAsync(dbContext.ConnectionString);
}
/// <summary>1. A thousand accounts in one call; no id comes back.</summary>
private static async Task Scenario1_ALoadWithoutIdsAsync(string connectionString)
{
Step("1. A load without ids");
var service = new ArxMsSqlDbService(connectionString, ArxSchemaCatalog.Create()
.Table("account", ArxIdColumn.Generated<long>("id"))
.Build());
var accounts = new List<ArxEntity>();
for (var i = 1; i <= 1000; i++)
{
var account = new ArxEntity("account");
account["name"] = $"Bulk account {i}";
account["account_number"] = $"ACC-F3{i:0000}";
account["employee_count"] = i % 50;
accounts.Add(account);
}
var ids = await service.CreateMultipleAsync(accounts, new ArxCreateMultipleOptions { ReturnIds = false });
Show($"{ids.Count} accounts created; ids returned: {ids.Count(x => x.HasValue)}");
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* SELECT count(*)
* FROM account
* WHERE account_number LIKE 'ACC-F3%';
* -- Expect: 1000.
* ===========================================================
*/
}
}
What every sample is given: the connection string (and the ISample interface the samples implement).
namespace ArxSamples.MSSQL;
/// <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 SqlClient 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.MSSQL;
/// <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. A load without ids
1000 accounts created; ids returned: 0