Reputation: 17064
I have entities stored in RavenDB (build #888). I need to change theirs IDs, because of database migration, connected with newer version of the application.
I've written sample function I'm using:
public bool Migrate()
{
using (var session = _store.OpenSession())
{
var users = session.Query<User>().ToList();
foreach (var user in users)
{
user.Id = user.Email;
}
session.SaveChanges();
}
}
Execution of this code results in an exception:
Status: System.InvalidOperationException: Entity App.Models.Entities.User had document key 'mydomain-mylogin' but now has document key property '[email protected]'.
You cannot change the document key property of a entity loaded into the session
at Raven.Client.Document.InMemoryDocumentSessionOperations.CreatePutEntityCommand(Object entity, DocumentMetadata documentMetadata)
at Raven.Client.Document.InMemoryDocumentSessionOperations.PrepareForEntitiesPuts(SaveChangesData result)
at Raven.Client.Document.InMemoryDocumentSessionOperations.PrepareForSaveChanges()
at Raven.Client.Document.DocumentSession.SaveChanges()
How can it be done ?
Upvotes: 3
Views: 734
Reputation: 17064
My current solution is copying current entities to temporary ones, changing desired properties, storing such new entities in database, and finally removing old ones:
using (var session = _store.OpenSession())
{
var users = session.Query<User>().ToList();
foreach (var user in users)
{
var newuser = new User
{
Id = user.Email,
DisplayName = user.DisplayName
};
session.Store(newuser);
session.Delete(user);
}
session.SaveChanges();
}
Upvotes: 4