Now that you have a more comprehensive understanding of the SurrealDB SDK for .NET, let’s create a simple project to get you started. This guide will walk you through creating a simple console application that uses the SurrealDB SDK for .NET to interact with a SurrealDB instance.
ImportantIf you want to see the final project for this guide, you can find it here and follow the instructions in the
README.md
file to get the project running.
This guide assumes the following:
>1.4.2
installed on your machine.Let’s start by creating a new console app.
# Create a new console app dotnet new console -o SurrealDbExample # Navigate into the generated directory cd SurrealDbExample # Add the SurrealDB SDK to your project via the dotnet CLI dotnet add package SurrealDb.Net
Open Program.cs
and replace everything in there with the following code to try out some basic operations using the SurrealDB SDK.
using SurrealDb.Net; using SurrealDb.Net.Models; using SurrealDb.Net.Models.Auth; using System.Text.Json; const string TABLE = "person"; using var db = new SurrealDbClient("ws://127.0.0.1:8000/rpc"); await db.SignIn(new RootAuth { Username = "root", Password = "root" }); await db.Use("test", "test"); var person = new Person { Title = "Founder & CEO", Name = new() { FirstName = "Tobie", LastName = "Morgan Hitchcock" }, Marketing = true }; var created = await db.Create(TABLE, person); Console.WriteLine(ToJsonString(created)); var updated = await db.Merge<ResponsibilityMerge, Person>( new() { Id = (TABLE, "jaime"), Marketing = true } ); Console.WriteLine(ToJsonString(updated)); var people = await db.Select<Person>(TABLE); Console.WriteLine(ToJsonString(people)); var queryResponse = await db.Query( $"SELECT Marketing, count() AS Count FROM type::table({TABLE}) GROUP BY Marketing" ); var groups = queryResponse.GetValue<List<Group>>(0); Console.WriteLine(ToJsonString(groups)); static string ToJsonString(object? o) { return JsonSerializer.Serialize(o, new JsonSerializerOptions { WriteIndented = true, }); } public class Person : Record { public string? Title { get; set; } public Name? Name { get; set; } public bool Marketing { get; set; } } public class Name { public string? FirstName { get; set; } public string? LastName { get; set; } } public class ResponsibilityMerge : Record { public bool Marketing { get; set; } } public class Group { public bool Marketing { get; set; } public int Count { get; set; } }
Then make sure your SurrealDB server is running on 127.0.0.1:8000
and run your app from the command line with:
dotnet run
Now that you have learned the basics of the .NET SDK for SurrealDB, you can learn more about the SDK and its methods in the methods section and data types section.