3

如何在 RavenDB 中以编程方式创建索引?

我试着按照这个例子

这是我的索引创建者:

public class MyIndex : Raven.Client.Indexes.AbstractIndexCreationTask<MyEntity>
{
    public MyIndex()
    {
        Map = col => col.Select(c => new
        {
            code = c.Code,
            len = c.Code.Length,
            sub = c.Code.Substring(0, 1)
        });
    }
}

这是调用者:

var store = new Raven.Client.Document.DocumentStore
{
    Url = "http://localhost:8080"
};
store.Initialize();

try
{
    using (var session = store.OpenSession("MyDB"))
    {
        Raven.Client.Indexes.IndexCreation.CreateIndexes(
            typeof(MyIndex).Assembly, store);
    }
}
finally
{
    store.Dispose();
}

索引已创建,但不是在 MyDB 中,而是在系统数据库中。

如何在 MyDB 中创建索引?我创建索引的方式是否正确?

4

2 回答 2

5

试试这个:在你的存储对象中指定数据库名称

var store = new Raven.Client.Document.DocumentStore
{
    Url = "http://localhost:8080",
    DefaultDatabase = "MyDB"
};
于 2013-07-02T15:01:54.700 回答
4

正如 MED 指出的,您可以在附加到文档存储时提供默认数据库。这样做时,您不再将数据库名称传递给该OpenSession方法。这是最简单的方法,如果您使用的是单个数据库,那么它是最好的答案(并且应该将其作为该问题的答案)。

但是,如果您需要使用多个数据库,因此无法使用该技术,那么您可以使用此辅助方法。

public static void CreateIndexes(Assembly assembly, IDocumentStore store,
                                                    string databaseName)
{
    var catalog = new AssemblyCatalog(assembly);
    var provider = new CompositionContainer(catalog);
    var commands = store.DatabaseCommands.ForDatabase(databaseName);
    IndexCreation.CreateIndexes(provider, commands, store.Conventions);
}

以与调用其他方法相同的方式调用它,但现在可以将数据库名称作为参数传递。

于 2013-07-02T15:28:48.707 回答