C# and .NET
Connect a C# and .NET application to TeselaDB with the official MongoDB driver.
Connect a C# and .NET application to TeselaDB with the official MongoDB driver for C# and .NET. TeselaDB presents itself as a mongos, so the driver works unchanged.
Requirements
- .NET 6 or later.
- The address of one or more nodes, a user with
readWriteon the database and thepki/ca.pemfile of the cluster.
Install the driver
Shell
dotnet add package MongoDB.DriverStore the connection string
Put the string in an environment variable instead of writing it in the code:
Shell
export TESELADB_URI="mongodb://user:<password>@node-01:27017,node-02:27017/shop?tls=true"Add the CA to the system certificates
The .NET driver checks the node certificate against the trusted certificates of the system, so the cluster CA has to be among them before your application opens its first connection to a node. On Linux, you add it like this:
Shell
sudo cp ca.pem /usr/local/share/ca-certificates/teseladb.crt
sudo update-ca-certificatesIn the connection string of your application keep only the tls=true option, without tlsCAFile.
Write and read a document
C#
var client = new MongoClient(Environment.GetEnvironmentVariable("TESELADB_URI"));
var orders = client.GetDatabase("shop").GetCollection<BsonDocument>("orders");
orders.InsertOne(new BsonDocument("total", 149.5));
Console.WriteLine(orders.CountDocuments(FilterDefinition<BsonDocument>.Empty));Check
The program prints the number of documents in orders, which grows by one each time you run it.
Common problems
- The connection closes before authenticating because
tls=trueis missing from the string. - The driver does not trust the node certificate because it does not have the CA of this cluster.