问题
I am using RavenDb embedded. As a part of my intergration tests I want to check objects are persisted. When I SaveChanges on an object, then retrieve it, it cannot be found unless I dispose my connection.
This does not work for me, as no files are returned
using (var session = _dataDocumentStore.Instance.OpenSession())
{
session.Store(file);
session.SaveChanges();
}
....
using (var session = _dataDocumentStore.Instance.OpenSession() )
{
return session.Query<File>().ToList();
}
I created a Flush method which disposes and recreates a EmbeddableDocumentStore which works, but as this is somthing that feels fundamental I may be going about things the wrong way:
public static IDocumentStore Initialize()
{
instance = new EmbeddableDocumentStore
{
DataDirectory = "App_Data/Database",
UseEmbeddedHttpServer = true,
};
instance.Initialize();
return instance;
}
public void Flush()
{
instance.Dispose();
Initialize();
}
How do you persist in RavenDB and then check it has been persisted? Any advice on this would be great
回答1:
Basically, the EmbeddableDocumentStore
takes longer to save and Index that new data, than saving and querying.
So when your tests say:-
- Store and SaveChanges.
- Load.
- Did this load?
the load completes waaay quicker than the indexing has had time to finish.
So, Like Daniel Lang said, u need to wait for stale results.
BUT .. you'll have to do that for -every- query you wish to check, in your code. So .. lets cheat (legally) :)
Tell your document store to ALWAYS wait for stale results, if something queries the store.
How?
// Initialise the Store.
var documentStore = new EmbeddableDocumentStore
{
RunInMemory = true
};
documentStore.Initialize();
// Force query's to wait for index's to catch up. Unit Testing only :P
documentStore.RegisterListener(new NoStaleQueriesListener());
....
#region Nested type: NoStaleQueriesListener
public class NoStaleQueriesListener : IDocumentQueryListener
{
#region Implementation of IDocumentQueryListener
public void BeforeQueryExecuted(IDocumentQueryCustomization queryCustomization)
{
queryCustomization.WaitForNonStaleResults();
}
#endregion
}
#endregion
Now to see this in action, check out RavenOverflow @ github. And the Tests project in that solution has all the love you might want :)

回答2:
The reason is, that ravens index is too stale to return something here. You need to do this:
session.Query<File>()
.Customize(x => x.WaitForNonStaleResultsAsOfLastWrite())
.ToList();
For further reading, go here: http://ravendb.net/docs/client-api/querying/stale-indexes
来源:https://stackoverflow.com/questions/9181204/ravendb-how-to-flush