MongoDB · Create
Create a record that refers to another
A document that refers to another: a contact of an account, in two scenarios. The reference is an ArxEntityReference made from the id CreateAsync returned; one to a collection the schema doesn't declare is refused before anything is sent.
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); SampleContext.Direct.cs (dbContext.Direct); MongoDirectHelper.cs (the checks behind dbContext.Direct).
dbContext.Direct is the samples' own checking code on the plain driver, not part of ARX: leave it out of your application.
1 A contact of an account
Create the account, then a contact whose account_id refers to it.
Already in scope: service (ArxMongoDbService)
var account = new ArxEntity("account");
account["name"] = "Litware, Inc.";
account["account_number"] = "ACC-M201";
ArxRecordId accountId = await service.CreateAsync(account);
var contact = new ArxEntity("contact");
contact["first_name"] = "Ada";
contact["last_name"] = "Lovelace";
contact["email"] = "ada@litware.example";
contact["account_id"] = new ArxEntityReference("account", accountId);
ArxRecordId contactId = await service.CreateAsync(contact);
Console.WriteLine($"created contact {contactId.AsString()} of account {accountId.AsString()}");Check it in the database
Run it in mongosh connected to the database, after the code has run.
db.contact.find({ email: "ada@litware.example" })Expect: 1 document, account_id an ObjectId equal to the account's _id.
2 A collection the schema doesn't declare
A reference to a collection the schema doesn't declare: ARX1005, nothing sent.
Already in scope: service (ArxMongoDbService)
var contact = new ArxEntity("contact");
contact["email"] = "nobody@litware.example";
contact["account_id"] = new ArxEntityReference("customer", "64b7f0c2a1b2c3d4e5f60718");
try
{
await service.CreateAsync(contact);
}
catch (ArxValidationException exception) when (exception.Code == ArxErrorCode.InvalidLookup)
{
Console.WriteLine(exception.Message);
}Check it in the database
Run it in mongosh connected to the database, after the code has run.
db.contact.find({ email: "nobody@litware.example" })Expect: no documents.
Good to know
MongoDB has no foreign keys: ARX checks the reference against the schema (the collection is declared, the id has its type) and stores it as the referenced id is stored, an ObjectId here.
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.MongoDb --version 1.0.0-rc.1 - Database: a MongoDB 7.0, a replica set (tested with 7.0.45, one node) database with the sample schema.
- Configuration: set
ARX_SAMPLES_MONGODBto 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,SampleContext.Direct.cs,MongoDirectHelper.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 and first remakes the sample database from sample-schema.json.
using ArxSamples.MongoDb;
using ArxSamples.MongoDb.Operations.Create.Basics;
// The connection string comes from the environment, never from the code (see "Configure the connection").
var connectionString = Environment.GetEnvironmentVariable("ARX_SAMPLES_MONGODB")
?? throw new InvalidOperationException("Set the ARX_SAMPLES_MONGODB environment variable to your MongoDB connection string.");
var dbContext = new SampleContext(connectionString);
// Every run starts from the sample data: this deletes and makes again what sample-schema.json lists
// (save the file in the project folder, see Get started).
await dbContext.Direct.ResetAsync();
await new Basic2_CreateWithALookup().RunAsync(dbContext);
The sample, as it is in the repository.
using ARX.SDK;
using ARX.SDK.MongoDb.Services;
using ARX.SDK.Services;
using static ArxSamples.MongoDb.SampleOutput;
namespace ArxSamples.MongoDb.Operations.Create.Basics;
/// <summary>
/// A document that refers to another: a contact of an account, in two scenarios. The reference is an
/// <see cref="ArxEntityReference"/> made from the id CreateAsync returned; one to a collection the schema doesn't declare
/// is refused before anything is sent.
/// </summary>
/// <remarks>
/// MongoDB has no foreign keys: ARX checks the reference against the schema (the collection is declared, the id has its
/// type) and stores it as the referenced id is stored, an ObjectId here.
/// </remarks>
public sealed class Basic2_CreateWithALookup : ISample
{
public string Name => "create-basics-2-create-with-a-lookup";
public string Title => "Create a record that refers to another";
public async Task RunAsync(SampleContext dbContext)
{
await Scenario1_AContactOfAnAccountAsync(dbContext.Service);
await Scenario2_AnUndeclaredCollectionAsync(dbContext.Service);
}
/// <summary>1. Create the account, then a contact whose account_id refers to it.</summary>
private static async Task Scenario1_AContactOfAnAccountAsync(ArxMongoDbService service)
{
Step("1. A contact of an account");
var account = new ArxEntity("account");
account["name"] = "Litware, Inc.";
account["account_number"] = "ACC-M201";
ArxRecordId accountId = await service.CreateAsync(account);
var contact = new ArxEntity("contact");
contact["first_name"] = "Ada";
contact["last_name"] = "Lovelace";
contact["email"] = "ada@litware.example";
contact["account_id"] = new ArxEntityReference("account", accountId);
ArxRecordId contactId = await service.CreateAsync(contact);
Show($"created contact {contactId.AsString()} of account {accountId.AsString()}");
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* db.contact.find({ email: "ada@litware.example" })
* -- Expect: 1 document, account_id an ObjectId equal to the account's _id.
* ===========================================================
*/
}
/// <summary>2. A reference to a collection the schema doesn't declare: ARX1005, nothing sent.</summary>
private static async Task Scenario2_AnUndeclaredCollectionAsync(ArxMongoDbService service)
{
Step("2. A collection the schema doesn't declare");
var contact = new ArxEntity("contact");
contact["email"] = "nobody@litware.example";
contact["account_id"] = new ArxEntityReference("customer", "64b7f0c2a1b2c3d4e5f60718");
try
{
await service.CreateAsync(contact);
}
catch (ArxValidationException exception) when (exception.Code == ArxErrorCode.InvalidLookup)
{
ShowError(exception);
}
/* ===========================================================
* [DIRECT QUERY CHECK]
* -----------------------------------------------------------
* db.contact.find({ email: "nobody@litware.example" })
* -- Expect: no documents.
* ===========================================================
*/
}
}
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 contact of an account
created contact 6af5339d4d3ca49045b87562 of account 6af5339d4d3ca49045b87561
> 2. A collection the schema doesn't declare
caught ArxValidationException: ARX1005 InvalidLookup: Lookup 'account_id' on 'contact' refers to table 'customer', which the schema doesn't declare.