本文介绍了嵌入式 RavenDb 的单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么当我使用这个单例时,负载检索总是为空?

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());
        }
    }
}

推荐答案

你说你的对象有一个整数 Id 字段.因此,假设您有一个 Foo 对象,其 Id 设置为 1.Raven 将使用文档 ID 为foos/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".

当您调用 Load 时,如果您传入整数 1,Raven 会将其正确转换回foos/1"字符串.但是因为您传入的是字符串1",所以 raven 只是假设该字符串代表整个文档 ID.在你的情况下,它没有.文档 id 为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.

此外,泛型 T 在存储中是多余的,您不妨直接使用对象.

Also, generic T is redundant on store, you might as well just use object.

但是请注意我关于不要在 Raven 中使用 Repository 模式的评论.它隐藏了 Raven 的绝大多数功能,并且在您开始查询时会给您带来麻烦.

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.

这篇关于嵌入式 RavenDb 的单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-21 02:23