RavenDB:将自动增量添加到ID以外的其他属性 [英] RavenDB: Add auto increment to other property than ID
本文介绍了RavenDB:将自动增量添加到ID以外的其他属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种方法可以在属性上放置一个属性,以告知RavenDB使用该属性,就像ID属性一样,并在其上自动增加计数?
Is there a way to put an attribute on a property to tell RavenDB to use this property just like the ID-property and put an auto increment on it?
伪代码:
public class MyObj {
public string Id { get; set; }
[Increment]
public int OtherProp { get; set; }
}
推荐答案
Dynamicus指向正确的解决方案,但是我想提供确切的示例代码,以帮助其他Stackoverflow用户,也可能使解决方案更易于搜索.
Dynamicus points to the correct solution, but I'd like to give the exact sample-code for helping other Stackoverflow-users and maybe also making the solution more searchable.
关于问题的示例代码,这是解决方案:
In relation to the question's example-code, here is the solution:
public class OtherPropIncrementListener : IDocumentStoreListener
{
HiLoKeyGenerator _generator;
IDocumentStore _store;
public OtherPropIncrementListener(IDocumentStore store)
{
this._store = store;
_generator = new HiLoKeyGenerator(store.DatabaseCommands, "MyObjs", 1);
}
public void AfterStore(string key, object entityInstance, RavenJObject metadata)
{
}
public bool BeforeStore(string key, object entityInstance, RavenJObject metadata, RavenJObject original)
{
var myObj = entityInstance as MyObj;
if(myObj != null && myObj.OtherProp == 0)
{
string documentKey = _generator.GenerateDocumentKey(_store.Conventions, entityInstance);
myObj.OtherProp = int.Parse(documentKey.Substring(documentKey.IndexOf("/") + 1));
return true;
}
return false;
}
}
然后,在初始化DocumentStore
之后,添加以下代码以使上面的侦听器起作用:
Then where after you initialize your DocumentStore
you add this code to make above listener work:
documentStore.RegisterListener(new OtherPropIncrementListener(documentStore));
这篇关于RavenDB:将自动增量添加到ID以外的其他属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文