Repository navigation
Architecture: Abstractions
This page covers the two faces of the framework's public surface — the consumer-facing API (what application code uses) and the provider-author contract (what a new backend has to implement) — plus the shared model and traversal-AST shapes that flow between them.
The consumer never sees the provider. They configure their model, get a typed accessor, and call methods on it. The surface is small.
Consumer subclasses GraphContext to declare their model:
public sealed class BlogGraphContext(GraphContextOptions options) : GraphContext(options)
{
protected override void OnModelCreating(IGraphModelBuilder modelBuilder) => modelBuilder
.ApplyConfiguration(new AuthorConfiguration())
.ApplyConfiguration(new PostConfiguration())
.ApplyConfiguration(new WroteConfiguration());
}
public sealed class AuthorConfiguration : INodeTypeConfiguration<Author>
{
public void Configure(INodeBuilder<Author> builder) => builder.HasKey(a => a.Id);
}The OnModelCreating callback runs once per context CLR type for the lifetime of the process (cached in ModelSource). The resulting IGraphModel is frozen and validated — duplicate labels, missing keys, and unregistered relationship endpoints fail at build time, not at first query.
context.Nodes<Author>().Add(author);
context.Nodes<Author>().Update(author);
context.Nodes<Author>().Remove(author);
context.Nodes<Author>().Merge(author);
Author? loaded = context.Nodes<Author>().FindById(authorId);
bool exists = context.Nodes<Author>().Exists(authorId);
foreach (Author a in context.Nodes<Author>().AsEnumerable()) { ... }
context.Edges<Wrote>().Connect(author, new Wrote { WrittenAt = DateTimeOffset.UtcNow }, post);
context.Edges<Wrote>().Disconnect(author, post);
foreach (Wrote w in context.Edges<Wrote>().AsEnumerable()) { ... }Post[] posts = [.. context.Traversal.Match()
.Node<Author>("a").Where(a => a.Name == "Ada")
.RelatedBy<Wrote, Post>("w").Outgoing().To("p")
.Where(p => p.PublishedAt > cutoff)
.OrderBy(p => p.PublishedAt)
.Take(10)
.Return<Post>("p")];Supported in the Where grammar: == / != / < / <= / > / >=, && / || / !, null checks, Contains / StartsWith / EndsWith. Anything else throws NotSupportedException — drop to RawStatement.Execute for richer queries.
// Implicit auto-transaction
await context.SaveChangesAsync();
// Explicit ambient transaction
await using IGraphTransaction tx = await context.BeginTransactionAsync();
context.Nodes<Author>().Add(author);
await context.SaveChangesAsync();
await tx.CommitAsync(); // or RollbackAsync, or just let dispose roll backOne ambient transaction at a time per context. Calling BeginTransaction while another is active throws GraphTransactionAlreadyActiveException. Concurrent transactions need separate contexts.
foreach (IReadOnlyDictionary<string, object?> row in context.RawStatement.Execute(
"MATCH (a:Author) WHERE a.name STARTS WITH $prefix RETURN a.name AS name",
new Dictionary<string, object?> { ["prefix"] = "A" }))
{
Console.WriteLine(row["name"]);
}The statement language is provider-native — Cypher for Neo4j and AGE, AQL for ArangoDB, op-coded JSON for in-memory. Rows arrive as IReadOnlyDictionary<string, object?> keyed by the returned alias.
A provider author implements five interfaces and one diagnostics class. The framework calls each at well-defined points and never inspects provider internals.
Translates a typed operation against an IGraphModel into a provider-specific DataStatement (statement text plus a parameter dictionary):
public interface IStatementEmitter
{
DataStatement EmitAdd<T>(IGraphModel model, T node);
DataStatement EmitUpdate<T>(IGraphModel model, T node);
DataStatement EmitRemove<T>(IGraphModel model, T node);
DataStatement EmitMerge<T>(IGraphModel model, T node);
DataStatement EmitConnect<TStart, TEdge, TEnd>(IGraphModel model, TStart start, TEdge edge, TEnd end);
DataStatement EmitDisconnect<TStart, TEdge, TEnd>(IGraphModel model, TStart start, TEnd end);
DataStatement EmitFindById<T>(IGraphModel model, object key);
DataStatement EmitExists<T>(IGraphModel model, object key);
DataStatement EmitAsEnumerableNodes<T>(IGraphModel model);
DataStatement EmitAsEnumerableEdges<T>(IGraphModel model);
DataStatement EmitTraversal(IGraphModel model, TraversalAst ast);
}Emitters are pure and stateless — same model + same node → same statement bytes. They walk INodeMetadata / IRelationshipMetadata / IPropertyMetadata to resolve labels, key configurations, and property storage names.
The wire layer. Receives a statement and parameter dictionary, yields rows:
public interface IRawStatementExecutor
{
IEnumerable<IReadOnlyDictionary<string, object?>> Execute(
string statement,
IReadOnlyDictionary<string, object?> parameters);
IAsyncEnumerable<IReadOnlyDictionary<string, object?>> ExecuteAsync(
string statement,
IReadOnlyDictionary<string, object?> parameters,
CancellationToken token = default);
}The executor consults IGraphTransactionOpener.Active to decide whether to enlist on an ambient transaction or open an auto-commit one. Async paths stream lazily; sync paths drain eagerly. Open-time failures wrap to RawStatementException; mid-stream failures propagate raw.
Projects rows back into CLR instances. Two reading modes:
- Alias-free, paired with the framework's typed-read emitters. The provider's emitter and materializer share an internal convention about row shape; the framework never names it.
- Alias-bearing, used by traversal returns when the consumer supplied a return alias.
public interface IResultMaterializer
{
T MaterializeNode<T>(IGraphModel model, IReadOnlyDictionary<string, object?> row);
T MaterializeEdge<T>(IGraphModel model, IReadOnlyDictionary<string, object?> row);
T MaterializeNodeAt<T>(IGraphModel model, IReadOnlyDictionary<string, object?> row, string alias);
T MaterializeEdgeAt<T>(IGraphModel model, IReadOnlyDictionary<string, object?> row, string alias);
bool ReadExists(IReadOnlyDictionary<string, object?> row);
}The transaction lifecycle:
public interface IGraphTransactionOpener
{
IGraphTransaction? Active { get; }
IGraphTransaction Open();
Task<IGraphTransaction> OpenAsync(CancellationToken token = default);
}
public interface IGraphTransaction : IDisposable, IAsyncDisposable
{
void Commit();
Task CommitAsync(CancellationToken token = default);
void Rollback();
Task RollbackAsync(CancellationToken token = default);
}V1 is one-ambient-at-a-time. Dispose without explicit Commit/Rollback performs best-effort rollback and logs at Warning.
Receives a TraversalAst, executes it, and materializes results:
public interface ITraversalTranslator
{
IEnumerable<TResult> Translate<TResult>(IGraphModel model, TraversalAst ast);
IAsyncEnumerable<TResult> TranslateAsync<TResult>(IGraphModel model, TraversalAst ast, CancellationToken token = default);
}Typically delegates: emitter.EmitTraversal for translation, executor for execution, materializer.MaterializeNodeAt / MaterializeEdgeAt for hydration.
The frozen model is the framework's vocabulary for "what types are registered and how do they map to the store":
public interface IGraphModel
{
IReadOnlyList<INodeMetadata> Nodes { get; }
IReadOnlyList<IRelationshipMetadata> Relationships { get; }
INodeMetadata GetNode(Type nodeType);
IRelationshipMetadata GetRelationship(Type edgeType);
}
public interface INodeMetadata
{
Type Type { get; }
string Label { get; }
IPropertyMetadata? Key { get; }
IReadOnlyList<IPropertyMetadata> Properties { get; }
}
public interface IRelationshipMetadata
{
Type StartType { get; }
Type EdgeType { get; }
Type EndType { get; }
string RelationshipType { get; }
IReadOnlyList<IPropertyMetadata> Properties { get; }
}
public interface IPropertyMetadata
{
PropertyInfo Property { get; }
string Name { get; }
bool Nullable { get; }
Func<object, object?> Getter { get; }
Action<object, object?> Setter { get; }
}Getter and Setter are compiled delegates — no per-call reflection on the hot path.
The fluent traversal builder accumulates state into a TraversalAst record. The translator receives it and lowers to the provider's native query shape:
public sealed record TraversalAst(
TraversalKind Kind, // Match | Merge | Create
IReadOnlyList<PatternSegment> Segments, // alternating Node, Rel, Node, Rel, …
IReadOnlyList<TraversalPredicate> Predicates,
string ReturnAlias)
{
public IReadOnlyList<TraversalOrdering> Orderings { get; init; } = [];
public int? Skip { get; init; }
public int? Take { get; init; }
}Pattern segments alternate node → relationship → node → relationship → node …:
public abstract record PatternSegment(string Alias);
public sealed record NodePatternSegment(Type NodeType, string Alias) : PatternSegment(Alias);
public sealed record RelationshipPatternSegment(Type EdgeType, string Alias, RelationshipDirection Direction) : PatternSegment(Alias);Predicates are a tree:
public abstract record TraversalPredicate;
public sealed record PropertyComparisonPredicate(string Alias, string ClrPropertyName, ComparisonOperator Operator, object? Value) : TraversalPredicate;
public sealed record StringComparisonPredicate(string Alias, string ClrPropertyName, StringComparisonOperator Operator, string Value) : TraversalPredicate;
public sealed record NullPredicate(string Alias, string ClrPropertyName, bool IsNull) : TraversalPredicate;
public sealed record AndPredicate(TraversalPredicate Left, TraversalPredicate Right) : TraversalPredicate;
public sealed record OrPredicate(TraversalPredicate Left, TraversalPredicate Right) : TraversalPredicate;
public sealed record NotPredicate(TraversalPredicate Inner) : TraversalPredicate;The AST shape was designed against Cypher patterns but has proven paradigm-agnostic in practice: the linear segment list translates cleanly to AQL's nested FOR loops (which are step-based, not pattern-based) without any AST changes. This is documented in detail on the ArangoDB provider page.