问题
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?
Pseudo-code:
public class MyObj {
public string Id { get; set; }
[Increment]
public int OtherProp { get; set; }
}
回答1:
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;
}
}
Then where after you initialize your DocumentStore
you add this code to make above listener work:
documentStore.RegisterListener(new OtherPropIncrementListener(documentStore));
回答2:
You can find the answer in RavenDB google groups. https://groups.google.com/forum/#!msg/ravendb/70xaVjoMidU/ssDs4mbKoxQJ
来源:https://stackoverflow.com/questions/12637947/ravendb-add-auto-increment-to-other-property-than-id