RavenDB: Add auto increment to other property than ID

▼魔方 西西 提交于 2020-02-21 04:46:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!