Here is a simple class:
public class Person
{
public int Id {get; set;}
public string Name {get; set;}
}
When I save this in RavenDB it gets some Id assinged, say it's 1, then this
var person = session.Load<Person>("Person/1")
returns person I specified but this
var person = session.Query<Person>().First(p => p.Id == 1)
errors out and says that 'sequence contains no elements'. I don't uderstand why.
Loading documents by their ID is an ACID operation. In other words, the moment you save the document, it is available for retrieval.
On the other hand, querying documents follows the no-sql concept of "eventual consistency". You are querying an index, and that index may or may not have had time to fully build.
In your example, the index is still stale. If you waited long enough, your query would return properly. Alternatively, you can tell Raven to wait by using the WaitForNonStaleResults customization, but this can have dangerous side effects - especially on a busy index. You can read more about stale index queries here: http://ravendb.net/docs/client-api/querying/stale-indexes
In general, if you know the Id of the document, you should always use .Load(). Reserve using .Query() for things that actually would require index lookup. In your case, a reasonable query might be:
var person = session.Query<Person>().Where(p => p.Name == "Joe").FirstOrDefault();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With