2012-09-28 91 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));