2012-09-28 50 views
2

有没有一种方法可以在属性上放置一个属性来告诉RavenDB使用这个属性,就像ID属性一样,并在其上放置一个自动增量?RavenDB:添加自动增量到ID以外的其他属性

伪代码:

public class MyObj { 
    public string Id { get; set; } 
    [Increment] 
    public int OtherProp { get; set; } 
} 

回答

2

Dynamicus points to the correct solution,但我想给出确切的样本代码帮助其他#1用户,也许也使解决方案更加搜索。

关于这个问题的例子代码,这里是解决方案:

public class OtherPropIncrementListener : IDocumentStoreListener 
{ 
    HiLoKeyGenerator _generator; 
    IDocumentStore _store; 
    public BlavenIdStoreListener(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添加此代码,以使上述听者工作:

documentStore.RegisterListener(new BlavenIdStoreListener(documentStore));