Domanda

Lets say we have a User class

    public class User
    {
        public User() {
          Created = DateTime.Now;
          Tags = new List<string>();
        }


        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime Created {get;set;}
        public IEnumerable<string> Tags {get; private set;}    
    }

And one might want a user to have an id like [FirstName]/[LastName] so we register an IdConvention like this:

     _documentStore
    .Conventions
    .RegisterIdConvention<User>(
      (dbname, commands, user) => user.FirstName +"/" + user.LastName ));

Now lets say you created a new user with a new set of tags attached. You want to store it in RavenDB if the User does not exist. However, if the User does exist you don't want to overwrite the existing Object as you want to keep the initial Created date. Therefore you only update the Tags enumeration with the values of the newly created User.

You might do something like this:

public void AddOrUpdateUser(User newUser) {
    using (var session = _documentStore.OpenSession())
                {

                    var existingUser = session.Load<User>("myFirstname/myLastname")
                    if(user != null) {
                     existingUser.Tags = user.Tags;
                    }
                   else {

                     session.Store(newUser);
                   }
                 session.SaveChanges();
                }
}

However, if for some reason I changed my IdConvention, I have had to update the code above as well. Is there a way to reference the IdConvention registered in order to calculate the id for the newUser Object. With this id value you could check wether an item exists or not rather than creating the Id by yourself.

È stato utile?

Soluzione

After registering an id convention, the GenerateDocumentKey method will use that convention instead of the default hilo generation scheme.

It needs some parameters, which are easiest to get at if you first cast the IDocumentSession to a real DocumentSession.

var s = ((DocumentSession) session);
var key = s.Conventions.GenerateDocumentKey(s.DatabaseName,
                                            s.DatabaseCommands,
                                            yourEntity);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top