迁移存储在RavenDB中的数据

时间:2012-05-17 11:52:01

标签: .net ravendb

我有实体存储在RavenDB(build#888)中。我需要更改他们的ID,因为数据库迁移与更新版本的应用程序相关联。

我写过我正在使用的示例函数:

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();
     }
}

执行此代码会导致异常:

Status: System.InvalidOperationException: Entity App.Models.Entities.User had document key 'mydomain-mylogin' but now has document key property 'mylogin@yahoo.com'.
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()

怎么做?

1 个答案:

答案 0 :(得分:3)

我目前的解决方案是将当前实体复制到临时实体,更改所需属性,将这些新实体存储在数据库中,最后删除旧实体:

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();
}