Seb*_*son 2 auto-increment ravendb
有没有办法在属性上放置一个属性来告诉 RavenDB 像 ID 属性一样使用这个属性并在它上面放置一个自动增量?
伪代码:
public class MyObj {
public string Id { get; set; }
[Increment]
public int OtherProp { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Dynamicus 指向正确的解决方案,但我想提供确切的示例代码以帮助其他 Stackoverflow 用户,并且可能还使解决方案更易于搜索。
关于问题的示例代码,这里是解决方案:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在初始化之后DocumentStore添加此代码以使上述侦听器工作:
documentStore.RegisterListener(new OtherPropIncrementListener(documentStore));
Run Code Online (Sandbox Code Playgroud)