Repository navigation
Example: A minimal movie graph
A complete, end-to-end example app showing how to declare a small domain model, configure it, wire it into DI, and use the typed surface for reads, writes, and traversals. The domain is the classic graph-database introduction: Movies, People, and ActedIn relationships.
Source layout:
MoviesApp/
├── MoviesApp.csproj
├── Domain/
│ ├── Movie.cs
│ ├── Person.cs
│ └── ActedIn.cs
├── Configuration/
│ ├── MovieConfiguration.cs
│ ├── PersonConfiguration.cs
│ └── ActedInConfiguration.cs
├── MovieGraphContext.cs
└── Program.cs
Plain CLR types. The framework requires a public or non-public parameterless constructor (for materialization) and a key property on every node type.
// Domain/Movie.cs
namespace MoviesApp.Domain;
public sealed class Movie
{
public Guid Id { get; init; }
public required string Title { get; set; }
public required int ReleaseYear { get; set; }
public string? Tagline { get; set; }
}// Domain/Person.cs
namespace MoviesApp.Domain;
public sealed class Person
{
public Guid Id { get; init; }
public required string Name { get; set; }
public required DateTimeOffset BornOn { get; init; }
}// Domain/ActedIn.cs
namespace MoviesApp.Domain;
public sealed class ActedIn
{
public required string Role { get; init; }
public required DateTimeOffset CastedAt { get; init; }
}INodeTypeConfiguration<T> declares a node's key (and any aliases). IRelationshipConfiguration<TStart, TEdge, TEnd> declares an edge's start / end node types — payload properties on the edge type are picked up by reflection.
// Configuration/MovieConfiguration.cs
using MoviesApp.Domain;
using OnixLabs.ElementFramework;
namespace MoviesApp.Configuration;
public sealed class MovieConfiguration : INodeTypeConfiguration<Movie>
{
public void Configure(INodeBuilder<Movie> builder) => builder.HasKey(m => m.Id);
}// Configuration/PersonConfiguration.cs
using MoviesApp.Domain;
using OnixLabs.ElementFramework;
namespace MoviesApp.Configuration;
public sealed class PersonConfiguration : INodeTypeConfiguration<Person>
{
public void Configure(INodeBuilder<Person> builder) => builder.HasKey(p => p.Id);
}// Configuration/ActedInConfiguration.cs
using MoviesApp.Domain;
using OnixLabs.ElementFramework;
namespace MoviesApp.Configuration;
public sealed class ActedInConfiguration : IRelationshipConfiguration<Person, ActedIn, Movie>
{
public void Configure(IRelationshipBuilder<Person, ActedIn, Movie> builder)
{
// No-op — relationship label defaults to the edge CLR type name ("ActedIn").
// Call builder.HasType("...") to override.
}
}The GraphContext subclass declares the model. OnModelCreating runs once per context CLR type for the lifetime of the process; the result is cached and frozen.
// MovieGraphContext.cs
using MoviesApp.Configuration;
using OnixLabs.ElementFramework;
namespace MoviesApp;
public sealed class MovieGraphContext(GraphContextOptions options) : GraphContext(options)
{
protected override void OnModelCreating(IGraphModelBuilder builder) => builder
.ApplyConfiguration(new MovieConfiguration())
.ApplyConfiguration(new PersonConfiguration())
.ApplyConfiguration(new ActedInConfiguration());
}Swap the Use* extension and you've swapped the backend — nothing in the consumer code below changes between providers.
// Program.cs
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Neo4j.Driver;
using MoviesApp;
using MoviesApp.Domain;
using OnixLabs.ElementFramework;
ServiceCollection services = new();
services.AddLogging(builder => builder.AddConsole().SetMinimumLevel(LogLevel.Information));
// Pick one — they're interchangeable as far as consumer code is concerned.
services.AddGraphContext<MovieGraphContext>((sp, builder) =>
builder
.UseLoggerFactory(sp.GetRequiredService<ILoggerFactory>())
.UseNeo4j(new Uri("bolt://localhost:7687"), AuthTokens.Basic("neo4j", "password")));
// services.AddGraphContext<MovieGraphContext>((sp, builder) => builder
// .UseLoggerFactory(sp.GetRequiredService<ILoggerFactory>())
// .UseAge("Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=postgres", "movies"));
// services.AddGraphContext<MovieGraphContext>((sp, builder) => builder
// .UseLoggerFactory(sp.GetRequiredService<ILoggerFactory>())
// .UseArango(new Uri("http://localhost:8529"), "_system", "root", "password"));
// services.AddGraphContext<MovieGraphContext>(builder => builder.UseInMemory("movies"));
await using ServiceProvider provider = services.BuildServiceProvider();
using IServiceScope scope = provider.CreateScope();
MovieGraphContext context = scope.ServiceProvider.GetRequiredService<MovieGraphContext>();
// If you're using the Arango provider, call this once at startup:
// await ArangoSchemaBootstrap.EnsureCollectionsAsync(
// context, new Uri("http://localhost:8529"), "_system", "root", "password");// Three people, two movies, four ActedIn relationships.
Person keanu = new() { Id = Guid.NewGuid(), Name = "Keanu Reeves", BornOn = new(1964, 9, 2, 0, 0, 0, TimeSpan.Zero) };
Person carrie = new(){ Id = Guid.NewGuid(), Name = "Carrie-Anne Moss", BornOn = new(1967, 8, 21, 0, 0, 0, TimeSpan.Zero) };
Person laurence = new(){Id = Guid.NewGuid(), Name = "Laurence Fishburne", BornOn = new(1961, 7, 30, 0, 0, 0, TimeSpan.Zero) };
Movie matrix = new() { Id = Guid.NewGuid(), Title = "The Matrix", ReleaseYear = 1999, Tagline = "Welcome to the Real World." };
Movie reloaded = new() { Id = Guid.NewGuid(), Title = "The Matrix Reloaded", ReleaseYear = 2003, Tagline = "Free your mind." };
context.Nodes<Person>().Add(keanu);
context.Nodes<Person>().Add(carrie);
context.Nodes<Person>().Add(laurence);
context.Nodes<Movie>().Add(matrix);
context.Nodes<Movie>().Add(reloaded);
context.Edges<ActedIn>().Connect(keanu, new ActedIn { Role = "Neo", CastedAt = new(1998, 3, 1, 0, 0, 0, TimeSpan.Zero) }, matrix);
context.Edges<ActedIn>().Connect(carrie, new ActedIn { Role = "Trinity", CastedAt = new(1998, 3, 1, 0, 0, 0, TimeSpan.Zero) }, matrix);
context.Edges<ActedIn>().Connect(laurence, new ActedIn { Role = "Morpheus", CastedAt = new(1998, 3, 1, 0, 0, 0, TimeSpan.Zero) }, matrix);
context.Edges<ActedIn>().Connect(keanu, new ActedIn { Role = "Neo", CastedAt = new(2001, 6, 1, 0, 0, 0, TimeSpan.Zero) }, reloaded);
int saved = await context.SaveChangesAsync();
Console.WriteLine($"Saved {saved} operations.");// FindById
Person? loaded = context.Nodes<Person>().FindById(keanu.Id);
Console.WriteLine($"Found: {loaded?.Name}");
// Exists
bool keanuExists = context.Nodes<Person>().Exists(keanu.Id);
bool ghostExists = context.Nodes<Person>().Exists(Guid.NewGuid());
Console.WriteLine($"Keanu exists: {keanuExists}, ghost exists: {ghostExists}");
// Enumerate every node of a type
Movie[] allMovies = [.. context.Nodes<Movie>().AsEnumerable()];
Console.WriteLine($"Catalogue has {allMovies.Length} movies.");Person[] matrixCast = [.. context.Traversal.Match()
.Node<Movie>("m").Where(m => m.Title == "The Matrix")
.RelatedBy<ActedIn, Person>("r").Incoming().To("p")
.Return<Person>("p")];
Console.WriteLine($"\nThe Matrix cast:");
foreach (Person p in matrixCast)
{
Console.WriteLine($" - {p.Name}");
}Movie[] keanuFilms = [.. context.Traversal.Match()
.Node<Person>("p").Where(p => p.Name == "Keanu Reeves")
.RelatedBy<ActedIn, Movie>("r").Outgoing().To("m")
.OrderBy(m => m.ReleaseYear)
.Return<Movie>("m")];
Console.WriteLine($"\nKeanu's filmography:");
foreach (Movie m in keanuFilms)
{
Console.WriteLine($" - ({m.ReleaseYear}) {m.Title}");
}ActedIn[] roles = [.. context.Traversal.Match()
.Node<Person>("p").Where(p => p.Name == "Keanu Reeves")
.RelatedBy<ActedIn, Movie>("r").Outgoing().To("m")
.Return<ActedIn>("r")];
Console.WriteLine($"\nKeanu's roles:");
foreach (ActedIn role in roles)
{
Console.WriteLine($" - {role.Role}");
}// Add a tagline to a movie that didn't have one
matrix.Tagline = "Welcome to the Real World.";
context.Nodes<Movie>().Update(matrix);
await context.SaveChangesAsync();
// Disconnect a relationship (removes every ActedIn edge from Keanu to Reloaded)
context.Edges<ActedIn>().Disconnect(keanu, reloaded);
await context.SaveChangesAsync();
// Remove a node
context.Nodes<Person>().Remove(laurence);
await context.SaveChangesAsync();await using IGraphTransaction tx = await context.BeginTransactionAsync();
try
{
context.Nodes<Movie>().Add(new Movie { Id = Guid.NewGuid(), Title = "The Matrix Revolutions", ReleaseYear = 2003 });
context.Edges<ActedIn>().Connect(keanu, new ActedIn { Role = "Neo", CastedAt = DateTimeOffset.UtcNow }, matrix);
await context.SaveChangesAsync();
await tx.CommitAsync();
}
catch
{
await tx.RollbackAsync();
throw;
}Or just let dispose roll back if you didn't reach the commit:
await using IGraphTransaction tx = await context.BeginTransactionAsync();
context.Nodes<Movie>().Add(new Movie { Id = Guid.NewGuid(), Title = "Tentative", ReleaseYear = 2030 });
await context.SaveChangesAsync();
// Forgot to call CommitAsync — dispose performs best-effort rollback.When the fluent traversal can't express what you need, drop to RawStatement.Execute. The query language is provider-native — the snippet below is Cypher (Neo4j or AGE):
foreach (IReadOnlyDictionary<string, object?> row in context.RawStatement.Execute(
"MATCH (p:Person)-[r:ActedIn]->(m:Movie) WHERE m.releaseYear > $year RETURN p.name AS person, count(m) AS films",
new Dictionary<string, object?> { ["year"] = 2000 }))
{
Console.WriteLine($" {row["person"]}: {row["films"]} film(s)");
}For ArangoDB the equivalent is AQL:
foreach (IReadOnlyDictionary<string, object?> row in context.RawStatement.Execute(
"""
FOR m IN @@movies
FILTER m.ReleaseYear > @year
FOR p IN 1..1 INBOUND m._id @@actedIn
COLLECT name = p.Name WITH COUNT INTO films
RETURN { person: name, films: films }
""",
new Dictionary<string, object?> { ["@movies"] = "Movie", ["@actedIn"] = "ActedIn", ["year"] = 2000 }))
{
Console.WriteLine($" {row["person"]}: {row["films"]} film(s)");
}The framework emits OpenTelemetry-compatible spans and counters without taking a dependency on the OpenTelemetry SDK. Wire your own exporter:
services.AddOpenTelemetry()
.WithTracing(tracing => tracing
.AddSource("OnixLabs.ElementFramework")
.AddSource("OnixLabs.ElementFramework.Neo4j") // or .AGE, .Arango — the one you're using
.AddOtlpExporter())
.WithMetrics(metrics => metrics
.AddMeter("OnixLabs.ElementFramework")
.AddMeter("OnixLabs.ElementFramework.Neo4j")
.AddOtlpExporter());You'll see spans for ElementFramework.SaveChanges, ElementFramework.BeginTransaction, ElementFramework.Transaction.Commit / .Rollback, plus provider-level Neo4j.ExecuteStatement and Neo4j.TranslateTraversal (or the AGE / Arango equivalents). Tags carry structural metadata only — counts, modes, kinds, alias names — never values.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<LangVersion>14</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="OnixLabs.ElementFramework" Version="1.0.0" />
<PackageReference Include="OnixLabs.ElementFramework.Neo4j" Version="1.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.7" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="10.0.7" />
</ItemGroup>
</Project>Swap OnixLabs.ElementFramework.Neo4j for .AGE, .Arango, or .InMemory to switch backends. The package list above is the minimum for Neo4j; AGE adds an Npgsql transitive dep, Arango adds ArangoDBNetStandard.