Compiled Queries and Query Plans
Marten has two different implementations for the "Specification" pattern that enable you to encapsulate all the filtering, ordering, and paging for a logically reusable data query into a single class:
- Compiled queries that help short circuit the LINQ processing with reusable "execution plans" for maximum performance, but are admittedly limited in terms of their ability to handle all possible LINQ queries or basically any dynamic querying whatsoever
- Query plans that can support anything that Marten itself can do, just without the magic LINQ query compilation optimization
Compiled Queries
WARNING
Don't use asynchronous Linq operators in the expression body of a compiled query. This will not impact your ability to use compiled queries in asynchronous querying.
WARNING
Compiled queries cannot use the recently added primary constructor feature in C#, and so far we don't even have a way to validate when you are using this feature in compiled query planning. Be warned.
Linq is easily one of the most popular features in .Net and arguably the one thing that other platforms strive to copy. We generally like being able to express document queries in compiler-safe manner, but there is a non-trivial cost in parsing the resulting Expression trees and then using plenty of string concatenation to build up the matching SQL query.
Fortunately, Marten supports the concept of a Compiled Query that you can use to reuse the SQL template for a given Linq query and bypass the performance cost of continuously parsing Linq expressions.
All compiled queries are classes that implement the ICompiledQuery<TDoc, TResult> interface shown below:
public interface ICompiledQuery<TDoc, TOut> : ICompiledQueryMarker where TDoc: notnull
{
Expression<Func<IMartenQueryable<TDoc>, TOut>> QueryIs();
}In its simplest usage, let's say that we want to find the first user document with a certain first name. That class would look like this:
public class FindByFirstName: ICompiledQuery<User, User>
{
public string FirstName { get; set; }
public Expression<Func<IMartenQueryable<User>, User>> QueryIs()
{
return q => q.FirstOrDefault(x => x.FirstName == FirstName);
}
}TIP
There are many more example compiled query classes in the acceptance tests for compiled queries within the Marten codebase.
So a couple things to note in the class above:
- The
QueryIs()method returns an Expression representing a Linq query FindByFirstNamehas a property (it could also be just a public field) calledFirstNamethat is used to express the filter of the query
To use the FindByFirstName query, just use the code below:
var justin = await session.QueryAsync(new FindByFirstName { FirstName = "Justin" });
var tamba = await session.QueryAsync(new FindByFirstName { FirstName = "Tamba" });Or to use it as part of a batched query, this syntax:
var batch = session.CreateBatchQuery();
var justin = batch.Query(new FindByFirstName { FirstName = "Justin" });
var tamba = batch.Query(new FindByFirstName { FirstName = "Tamba" });
await batch.Execute();
(await justin).Id.ShouldBe(user1.Id);
(await tamba).Id.ShouldBe(user2.Id);Recommended setup: enable the source generator
TIP
The source-generated path described in this section is the supported way to use compiled queries. Queries the generator can't see at build time (no [JasperFxAssembly] marker, or shapes the generator skips) fall through to a reflection + FastExpressionCompiler-built descriptor at first use — no Roslyn, no pre-built artifacts.
Marten ships a Roslyn source generator (Marten.SourceGenerator) that emits the per-ICompiledQuery<,> scaffolding at compile time. Opt-in is implicit — add two things to the project that declares your compiled query types and the runtime picks the source-generated path automatically:
<!-- in your .csproj -->
<ItemGroup>
<PackageReference Include="Marten.SourceGenerator" PrivateAssets="all" />
</ItemGroup>// in any file in the same assembly (e.g., AssemblyInfo.cs)
[assembly: JasperFx.JasperFxAssembly]With both present, the generator emits a typed handler for every ICompiledQuery<TDoc, TOut> in the assembly and registers it with the Marten runtime via a [ModuleInitializer] that fires at assembly load.
What this gets you compared to the reflection-built fallback:
- No
FastExpressionCompilerfor the per-query parameter binder. The generator emits a direct property-read switch — ~31% faster steady-state per call. - AOT-publishable for the common cases. No dynamic-codegen surface for queries the source-gen path covers.
The runtime builds the descriptor reflectively (no Roslyn — FastExpressionCompiler + a manual fallback inside RuntimeCompiledQueryDescriptorFactory) in three documented cases:
- Plans whose SQL needs an
ICompiledQueryAwareFilter(stringContains/StartsWith/EndsWith,HashSet<T>.Containswith JSONB containment,Dictionary<,>.ContainsKey, child-collection JsonPath counts). - Generic or nested
ICompiledQuery<,>types — the generator skips both shapes for now. - Compiled queries declared in an assembly without
[JasperFxAssembly].
The source generator is additive — adding it never breaks an existing compiled query; removing it just shifts that query to the reflection-built fallback at first use. Tracking issue: #4405.
How Does It Work?
The first time that Marten encounters a new type of ICompiledQuery, it builds a "plan" for the query by:
- Finding all public readable properties or fields on the compiled query type that would be potential parameters. Members marked with the
[MartenIgnore]attribute are skipped. - Constructing a new instance of the same type and assigning unique values itself. It falls back to the query object you passed in only when it cannot build that instance, and then only if your object has unique values across each parameter member. Marten generates the values so that none of them can be mistaken for a literal in your query.
- Parsing the expression returned from
QueryIs()to derive the SQL command + the parameter slots Marten needs to fill at execution time. - Matching the unique member values back to the command's parameter values to map query members to database parameters by index.
How Marten then dispatches the per-call hot path depends on whether the source generator is in play:
- Source-generated dispatch (default when the
Marten.SourceGeneratoranalyzer reference +[assembly: JasperFxAssembly]are present, see Recommended setup above). The generator emits a typed{Query}_CompiledQueryHandlerclass for everyICompiledQuery<,>in the assembly, plus a[ModuleInitializer]that registers the handler with Marten's runtimeCompiledQueryHandlerRegistryat assembly load. When Marten sees the registered query type, it routes through the generator-emitted parameter binder (direct field/property reads — no reflection at runtime). - Reflection-built fallback. When the source generator hasn't registered a descriptor for the query type — assembly without
[JasperFxAssembly], shape the generator skips, or runtime-registered query — Marten walks the freshly-built plan reflectively, compiles a per-query parameter binder viaFastExpressionCompiler, and caches the resulting descriptor in the same registry. No Roslyn, no pre-built artifacts.
On subsequent calls to the same compiled query type, both paths just reuse the cached handler — the SQL command + parameter binder are remembered for the life of the DocumentStore.
You may need to help Marten out a little bit with the compiled query support in determining unique parameter values to use during query planning by implementing the new Marten.Linq.IQueryPlanning interface on your compiled query type. Consider this example query that uses paging:
public class CompiledTimeline : ICompiledListQuery<TimelineItem>, IQueryPlanning
{
public int PageSize { get; set; } = 20;
[MartenIgnore] public int Page { private get; set; } = 1;
public int SkipCount => (Page - 1) * PageSize;
public string Type { get; set; }
public Expression<Func<IMartenQueryable<TimelineItem>, IEnumerable<TimelineItem>>> QueryIs() =>
query => query.Where(i => i.Event == Type).Skip(SkipCount).Take(PageSize);
public void SetUniqueValuesForQueryPlanning()
{
Page = 3; // Setting Page to 3 forces the SkipCount and PageSize to be different values
PageSize = 20; // This has to be a positive value, or the Take() operator has no effect
Type = Guid.NewGuid().ToString();
}
// And hey, if you have a public QueryStatistics member on your compiled
// query class, you'll get the total number of records
public QueryStatistics Statistics { get; } = new QueryStatistics();
}Pay close attention to the SetUniqueValuesForQueryPlanning() method. That has absolutely no other purpose but to help Marten create a compiled query plan for the CompiledTimeline type.
What is Supported?
To the best of our knowledge and testing, you may use any Linq feature that Marten supports within a compiled query. So any combination of:
Select()transformsFirst/FirstOrDefault()Single/SingleOrDefault()Where()Include()OrderBy/OrderByDescendingetc.Count()Any()Skip()andTake()for pagination, with aQueryStatisticsmember for the total count (see Querying for Paginated Results)
To get the results as raw JSON, run the compiled query with ToJsonMany(), ToJsonOne(), StreamJsonMany() or StreamJsonOne(), as shown in Querying for Results as JSON.
As for limitations,
- You cannot use the Linq
ToArray()orToList()operators. See the next section for an explanation of how to query for multiple results withICompiledListQuery. - The compiled query planning cannot match
boolor nullable (int?,DateTime?and so on) fields or properties to command arguments, so they cannot be used as parameters. Marten throws anInvalidCompiledQueryExceptionnaming them when it builds the plan QueryIs()has to read each value directly from a member of the query object. A value computed from members inside the expression, such asFirst + Second,Name.ToUpper()ornew List<string> { First, Second }, is refused with anInvalidCompiledQueryExceptionwhen the plan is built: it matches no member, so it would be frozen at its planning value. Compute it in a property of the query instead, the waySkipCountdoes in the example above. Conversions that keep a member's value, like comparing anintmember to anint?field, and inline arrays of members,new[] { First, Second }, are fine (see #5711)- A
Select()projection that runs on the client (see Projections That Can't Be Expressed in SQL) cannot read a member of the query object. Marten throwsInvalidCompiledQueryExceptionwhen it builds the plan, because the compiled projection would keep the value from the first execution forever. A client-side projection that only reads the document is fine (see #5233) Join(),LeftJoin()andRightJoin()are refused in a compiled query, whose only source is its own parameter. See Join, LeftJoin, RightJoin and FullJoin- You cannot use any asynchronous operators. So in all cases, use the synchronous operator equivalent. So
FirstOrDefault(), but notFirstOrDefaultAsync().QueryIs()only builds an expression and never executes it, so Marten 10's refusal of synchronous LINQ does not apply there. This does not preclude you from using compiled queries in asynchronous querying
Querying for Multiple Results
To query for multiple results, you need to just return the raw IQueryable<T> as IEnumerable<T> as the result type. You cannot use the ToArray() or ToList() operators. Marten refuses them. As a convenience mechanism, Marten supplies these helper interfaces:
If you are selecting the whole document without any kind of Select() transform, you can use this interface:
public interface ICompiledListQuery<TDoc>: ICompiledListQuery<TDoc, TDoc> where TDoc : notnull
{
}A sample usage of this type of query is shown below:
public class UsersByFirstName: ICompiledListQuery<User>
{
public static int Count;
public string FirstName { get; set; }
public Expression<Func<IMartenQueryable<User>, IEnumerable<User>>> QueryIs()
{
return query => query.Where(x => x.FirstName == FirstName);
}
}If you do want to use a Select() transform, use this interface:
public interface ICompiledListQuery<TDoc, TOut>: ICompiledQuery<TDoc, IEnumerable<TOut>> where TDoc : notnull
{
}A sample usage of this type of query is shown below:
public class UserNamesForFirstName: ICompiledListQuery<User, string>
{
public Expression<Func<IMartenQueryable<User>, IEnumerable<string>>> QueryIs()
{
return q => q
.Where(x => x.FirstName == FirstName)
.Select(x => x.UserName);
}
public string FirstName { get; set; }
}Querying for Related Documents with Include()
A compiled query can include related documents the same way a simple query does, with the Include() method on the query:
[Fact]
public async Task simple_compiled_include_for_a_single_document()
{
var user = new User();
var issue = new Issue { AssigneeId = user.Id, Title = "Garage Door is busted" };
using var session = theStore.IdentitySession();
session.Store<object>(user, issue);
await session.SaveChangesAsync();
using var query = theStore.QuerySession();
var issueQuery = new IssueByTitleWithAssignee { Title = issue.Title };
var issue2 = await query.QueryAsync(issueQuery);
issueQuery.Included.ShouldNotBeNull();
issueQuery.Included.Single().Id.ShouldBe(user.Id);
issue2.ShouldNotBeNull();
}
public class IssueByTitleWithAssignee: ICompiledQuery<Issue>
{
public string Title { get; set; }
public IList<User> Included { get; private set; } = new List<User>();
public Expression<Func<IMartenQueryable<Issue>, Issue>> QueryIs()
{
return query => query
.Include(x => x.AssigneeId, Included)
.Single(x => x.Title == Title);
}
}In this example, the query has an Included property which receives the included Assignee / User, through Include(x => x.AssigneeId, Included). The list that receives the included documents has to be a member of the query object, so that Marten knows where to put them when it runs the plan again.
You can chain Include() calls to include more than one document type.
Querying for Multiple Related Documents
Fetching "included" documents could also be done when you wish to include multiple documents. So picking up the same example, if you wish to get a list of Issues and for every Issue you wish to retrieve its' Assignee / User, in your compiled query you should have a list of Users like so:
public class IssueWithUsers: ICompiledListQuery<Issue>
{
public List<User> Users { get; set; } = new List<User>();
// Can also work like that:
//public List<User> Users => new List<User>();
public Expression<Func<IMartenQueryable<Issue>, IEnumerable<Issue>>> QueryIs()
{
return query => query.Include(x => x.AssigneeId, Users);
}
}
[Fact]
public async Task compiled_include_to_list()
{
var user1 = new User();
var user2 = new User();
var issue1 = new Issue { AssigneeId = user1.Id, Title = "Garage Door is busted" };
var issue2 = new Issue { AssigneeId = user2.Id, Title = "Garage Door is busted" };
var issue3 = new Issue { AssigneeId = user2.Id, Title = "Garage Door is busted" };
using var session = theStore.IdentitySession();
session.Store(user1, user2);
session.Store(issue1, issue2, issue3);
await session.SaveChangesAsync();
using var querySession = theStore.QuerySession();
var compiledQuery = new IssueWithUsers();
var issues = await querySession.QueryAsync(compiledQuery);
compiledQuery.Users.Count.ShouldBe(2);
issues.Count().ShouldBe(3);
compiledQuery.Users.Any(x => x.Id == user1.Id);
compiledQuery.Users.Any(x => x.Id == user2.Id);
}Note that you could either have the list instantiated or at least make sure the property has a setter as well as a getter (we've got your back).
As with the simple include queries, you could also use a Dictionary with a key type corresponding to the Id of the document- the dictionary value type:
public class IssueWithUsersById: ICompiledListQuery<Issue>
{
public IDictionary<Guid, User> UsersById { get; set; } = new Dictionary<Guid, User>();
// Can also work like that:
//public List<User> Users => new Dictionary<Guid,User>();
public Expression<Func<IMartenQueryable<Issue>, IEnumerable<Issue>>> QueryIs()
{
return query => query.Include(x => x.AssigneeId, UsersById);
}
}
[Fact]
public async Task compiled_include_to_dictionary()
{
var user1 = new User();
var user2 = new User();
var issue1 = new Issue { AssigneeId = user1.Id, Title = "Garage Door is busted" };
var issue2 = new Issue { AssigneeId = user2.Id, Title = "Garage Door is busted" };
var issue3 = new Issue { AssigneeId = user2.Id, Title = "Garage Door is busted" };
using var session = theStore.IdentitySession();
session.Store(user1, user2);
session.Store(issue1, issue2, issue3);
await session.SaveChangesAsync();
using var querySession = theStore.QuerySession();
var compiledQuery = new IssueWithUsersById();
var issues = await querySession.QueryAsync(compiledQuery);
issues.ShouldNotBeEmpty();
compiledQuery.UsersById.Count.ShouldBe(2);
compiledQuery.UsersById.ContainsKey(user1.Id).ShouldBeTrue();
compiledQuery.UsersById.ContainsKey(user2.Id).ShouldBeTrue();
}Querying for Paginated Results
Marten compiled queries also support queries for paginated results, where you could specify the page number and size, as well as getting the total count. A simple example of how this can be achieved as follows:
public class TargetPaginationQuery: ICompiledListQuery<Target>
{
public TargetPaginationQuery(int pageNumber, int pageSize)
{
PageNumber = pageNumber;
PageSize = pageSize;
}
public int PageNumber { get; set; }
public int PageSize { get; set; }
// QueryIs() has to read each value straight from a member, so compute the offset here
public int SkipCount => (PageNumber - 1) * PageSize;
public QueryStatistics Stats { get; } = new QueryStatistics();
public Expression<Func<IMartenQueryable<Target>, IEnumerable<Target>>> QueryIs()
{
return query => query
.Where(x => x.Number > 10)
.Skip(SkipCount)
.Take(PageSize);
}
}To get the QueryStatistics out, expose a QueryStatistics property on the query, as Stats above. Marten fills it in when the query runs, the same way it handles the members that receive Include() results.
Querying for a Single Document
If you are querying for a single document with no transformation, you can use this interface as a convenience:
public interface ICompiledQuery<TDoc>: ICompiledQuery<TDoc, TDoc> where TDoc : notnull
{
}And an example:
public class FindUserByAllTheThings: ICompiledQuery<User>
{
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Expression<Func<IMartenQueryable<User>, User>> QueryIs()
{
return query =>
query.Where(x => x.FirstName == FirstName && Username == x.UserName)
.Where(x => x.LastName == LastName)
.Single();
}
}Querying for Results as JSON
Any compiled query can return its results as raw JSON instead of documents. The query class does not change. Run it with one of these methods on the session:
| Method | Returns |
|---|---|
ToJsonMany(query) | The results as a JSON array string |
StreamJsonMany(query, stream) | Writes the JSON array to a Stream, and returns the number of documents written |
ToJsonOne(query) | One document as a JSON string, or null if nothing matched |
StreamJsonOne(query, stream) | Writes one document to a Stream, and returns false if nothing matched |
Here are the two compiled queries used below, one for a list and one for a single document:
public class FindJsonOrderedUsersByUsername: ICompiledListQuery<User>
{
public string FirstName { get; set; }
Expression<Func<IMartenQueryable<User>, IEnumerable<User>>> ICompiledQuery<User, IEnumerable<User>>.QueryIs()
{
return query =>
query.Where(x => FirstName == x.FirstName)
.OrderBy(x => x.UserName);
}
}public class FindJsonUserByUsername: ICompiledQuery<User>
{
public string Username { get; set; }
Expression<Func<IMartenQueryable<User>, User>> ICompiledQuery<User, User>.QueryIs()
{
return query =>
query.Where(x => Username == x.UserName).Single();
}
}And the calls that run them as JSON:
public async Task compiled_query_as_json(IQuerySession session, Stream destination)
{
// A list query as a JSON array string
var json = await session.ToJsonMany(new FindJsonOrderedUsersByUsername { FirstName = "Jeremy" });
// Or written straight to a stream. Returns the number of documents written
var count = await session.StreamJsonMany(new FindJsonOrderedUsersByUsername { FirstName = "Jeremy" },
destination);
// A single document query as JSON, or null if nothing matched
var one = await session.ToJsonOne(new FindJsonUserByUsername { Username = "jdm" });
// Or written straight to a stream. Returns false if nothing matched
var found = await session.StreamJsonOne(new FindJsonUserByUsername { Username = "jdm" }, destination);
}The JSON array has the documents comma separated and wrapped in square brackets.
Using with QueryStatistics
Compiled queries can be used with the QueryStatistics paging helper. You just need to have a public member on your compiled query class of type QueryStatistics with a value. Marten will do the rest and use that object to collect the total number of rows in the database when the query is executed. Here's an example from the Marten tests:
public class TargetsInOrder: ICompiledListQuery<Target>
{
// This is all you need to do
public QueryStatistics Statistics { get; } = new QueryStatistics();
public int PageSize { get; set; } = 20;
public int Start { get; set; } = 5;
Expression<Func<IMartenQueryable<Target>, IEnumerable<Target>>> ICompiledQuery<Target, IEnumerable<Target>>.
QueryIs()
{
return q => q
.OrderBy(x => x.Id).Skip(Start).Take(PageSize);
}
}And when used in the actual test:
[Fact]
public async Task use_compiled_query_with_statistics()
{
await theStore.Advanced.Clean.DeleteDocumentsByTypeAsync(typeof(Target));
var targets = Target.GenerateRandomData(100).ToArray();
await theStore.BulkInsertAsync(targets);
var query = new TargetsInOrder { PageSize = 10, Start = 20 };
var results = await theSession.QueryAsync(query);
// Verifying that the total record count in the database matching
// the query is determined when this is executed
query.Statistics.TotalResults.ShouldBe(100);
}Query Plans 7.25
INFO
The query plan concept was created specifically to help a JasperFx client try to eliminate their custom repository wrappers around Marten and to better utilize batch querying.
TIP
Batch querying is a great way to improve the performance of your system.
A query plan is another flavor of "Specification" for Marten that just enables you to bundle up query logic that can be reused within your codebase without having to create wrappers around Marten itself. To create a reusable query plan, implement the IQueryPlan<T> interface where T is the type of the result you want. Here's a simplistic sample from the tests:
public class ColorTargets: QueryListPlan<Target>
{
public Colors Color { get; }
public ColorTargets(Colors color)
{
Color = color;
}
// All we're doing here is just turning around and querying against the session
// All the same though, this approach lets you do much more runtime logic
// than a compiled query can
public override IQueryable<Target> Query(IQuerySession session)
{
return session.Query<Target>().Where(x => x.Color == Color).OrderBy(x => x.Number);
}
}
// The above is short hand for:
public class LonghandColorTargets: IQueryPlan<IReadOnlyList<Target>>, IBatchQueryPlan<IReadOnlyList<Target>>
{
public Colors Color { get; }
public LonghandColorTargets(Colors color)
{
Color = color;
}
public Task<IReadOnlyList<Target>> Fetch(IQuerySession session, CancellationToken token)
{
return session
.Query<Target>()
.Where(x => x.Color == Color)
.OrderBy(x => x.Number)
.ToListAsync(token: token);
}
public Task<IReadOnlyList<Target>> Fetch(IBatchedQuery batch)
{
return batch
.Query<Target>()
.Where(x => x.Color == Color)
.OrderBy(x => x.Number)
.ToList();
}
}And then use that like so:
public static async Task use_query_plan(IQuerySession session, CancellationToken token)
{
var targets = await session
.QueryByPlanAsync(new ColorTargets(Colors.Blue), token);
}There is also a similar interface for usage with batch querying:
/// <summary>
/// Marten's concept of the "Specification" pattern for reusable
/// queries within Marten batched queries. Use this for operations that cannot be supported by Marten compiled queries
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IBatchQueryPlan<T>
{
Task<T> Fetch(IBatchedQuery query);
}And because we expect this to be very common, there is convenience base class named QueryListPlan<T> for querying lists of T data that can be used for both querying directly against an IQuerySession and for batch querying. The usage within a batched query is shown below from the Marten tests:
[Fact]
public async Task use_as_batch()
{
await theStore.Advanced.Clean.DeleteDocumentsByTypeAsync(typeof(Target));
var targets = Target.GenerateRandomData(1000).ToArray();
await theStore.BulkInsertDocumentsAsync(targets);
// Start a batch query
var batch = theSession.CreateBatchQuery();
// Using the ColorTargets plan twice, once for "Blue" and once for "Green" target documents
var blueFetcher = batch.QueryByPlan(new ColorTargets(Colors.Blue));
var greenFetcher = batch.QueryByPlan(new ColorTargets(Colors.Green));
// Execute the batch query
await batch.Execute();
// The batched querying in Marten is essentially registering a "future"
// for each query, so we'll await each task from above to get at the actual
// data returned from batch.Execute() above
var blues = await blueFetcher;
var greens = await greenFetcher;
// And the assertion part of our arrange, act, assertion test
blues.ShouldNotBeEmpty();
greens.ShouldNotBeEmpty();
var expectedBlues = targets.Where(x => x.Color == Colors.Blue).OrderBy(x => x.Number);
var expectedReds = targets.Where(x => x.Color == Colors.Green).OrderBy(x => x.Number);
blues.Select(x => x.Id).ShouldBe(expectedBlues.Select(x => x.Id));
greens.Select(x => x.Id).ShouldBe(expectedReds.Select(x => x.Id));
}Query Plans for Event Streams
Marten ships two concrete query plans for the raw event stream fetches so that they can also be used as batchable specifications. FetchStreamStatePlan fetches the high level StreamState metadata about a single stream (yielding null when the stream does not exist), while FetchStreamPlan fetches the raw events of a single stream (yielding an empty list when the stream does not exist) with support for the optional version, timestamp, and fromVersion filters of FetchStreamAsync(). Both plans accept either a Guid stream id or a string stream key to cover both stream identity styles.
Using FetchStreamPlan standalone against a session:
[Fact]
public async Task fetch_stream_by_query_plan()
{
var streamId = theSession.Events.StartStream<Quest>(new QuestStarted { Name = "Destroy the One Ring" },
new MembersJoined(1, "Hobbiton", "Frodo", "Sam"),
new MembersJoined(2, "Bree", "Aragorn")).Id;
await theSession.SaveChangesAsync();
var events = await theSession.QueryByPlanAsync(new FetchStreamPlan(streamId));
events.Count.ShouldBe(3);
events[0].Data.ShouldBeOfType<QuestStarted>();
}And because both plans also implement IBatchQueryPlan<T>, they can be combined with any other registered queries within a batched query to fetch a stream's state and its raw events in one database round trip:
[Fact]
public async Task use_both_plans_in_one_batch()
{
var streamId = theSession.Events.StartStream<Quest>(new QuestStarted { Name = "Destroy the One Ring" },
new MembersJoined(1, "Hobbiton", "Frodo", "Sam")).Id;
await theSession.SaveChangesAsync();
// Start a batch query
var batch = theSession.CreateBatchQuery();
// Fetching the stream state and the raw events of the same stream
// in one database round trip
var stateFetcher = batch.QueryByPlan(new FetchStreamStatePlan(streamId));
var eventsFetcher = batch.QueryByPlan(new FetchStreamPlan(streamId));
// Execute the batch query
await batch.Execute();
var state = await stateFetcher;
var events = await eventsFetcher;
state.ShouldNotBeNull();
state.Version.ShouldBe(2);
events.Count.ShouldBe(2);
}
