问题
Why when I use this singleton the load retreive always null?
public class DataLayer
{
private EmbeddableDocumentStore d;
private static object lockerSingleton = new object();
private static DataLayer _current;
public static DataLayer RavenDB
{
get
{
lock (lockerSingleton)
{
if (_current == null)
_current = new DataLayer();
}
return _current;
}
}
public DataLayer()
{
d = new EmbeddableDocumentStore() { DataDirectory = "csv" };
d.Initialize();
}
public void store<T>(T obj)
{
using (var session = d.OpenSession())
{
session.Store(obj);
session.SaveChanges();
}
}
public T retrieve<T>(object ID)
{
using (var session = d.OpenSession())
{
return session.Load<T>(ID.ToString());
}
}
}
回答1:
You say your object has an integer Id field. So let's say you have an object of Foo with its Id set to 1. Raven will store your document with the document id of "foos/1".
When you are calling Load, if you pass in the integer 1, Raven will properly translate that back to the "foos/1" string. But because you are passing in the string "1", raven just assumes that the string represents the entire document id. In your case, it does not. A document does not exist with the document id of "1", so you get a null.
Also, generic T is redundant on store, you might as well just use object.
But please, heed my comment about not using the Repository pattern with Raven. It hides the vast majority of Raven's functionality, and will get you into trouble when you start querying.
来源:https://stackoverflow.com/questions/12961129/singleton-for-embeded-ravendb