1

I have sets of entities all of them are derived from abstract class

public abstract class NamedEntity : INamedEntity
{
    #region Public Properties

    public string Description { get; set; }

    public string Id { get; set; }

    public string Name { get; set; }

    #endregion
}

When I persist all entities I want to use Name field as a key, so I override DocumentKeyGenerator and provide such implementation:

    store.Conventions.DocumentKeyGenerator = entity =>
        {
            var namedEntity = entity as NamedEntity;

            if (namedEntity != null)
            {
                return string.Format("{0}/{1}", store.Conventions.GetTypeTagName(entity.GetType()), namedEntity.Name);
            }

            return string.Format("{0}/", store.Conventions.GetTypeTagName(entity.GetType()));
        };

It works fine when I persist the list of entities for the first time, but if I want to persist them again I get an exception

PUT attempted on document 'xxxxx' using a non current etag

I just started using RavenDB, so I cannot understand what I am doing wrong?

Jevgenij Nekrasov
  • 2,690
  • 3
  • 30
  • 51

1 Answers1

2

Just a guess, but it's probably not with your key generation, but how you are storing them.

On first usage you probably have something like:

var myEntity = new MyEntity(...);
session.Store(myEntity);
...
session.SaveChanges();

That part is fine, but on subsequent usage, you should not be doing the same thing. Instead, it should be more like this:

var myEntity = session.Load<MyEntity>("myentities/foobar");
myEntity.Something = 123;
...
session.SaveChanges();

Note there is no call to .Store() when making changes. This is because the entity is "tracked" by the session, and all changes to it are automatically persisted when you call .SaveChanges()

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • so if I get the set of entities from external source and just want to refresh my persisted entities, should I iterate all of them, reassign their values and then SaveChanges? Also if I let RavenDB to generate unique keys for my entities my code works just fine, could I repeat such behavior generating my own keys? What are the differences? – Jevgenij Nekrasov Oct 17 '12 at 17:24
  • You could indeed do that. If you have a lot of documents to change all at once, you might want to investigate the patching API instead. http://ravendb.net/docs/client-api/partial-document-updates – Matt Johnson-Pint Oct 17 '12 at 17:29
  • If you let raven generate unique ids, and you store a new entity, it may not throw the exception you saw, but you are really storing a new document, not updating an existing one. There will be two when you are done. – Matt Johnson-Pint Oct 17 '12 at 17:30