2

我有实体存储在 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()

如何做呢 ?

4

1 回答 1

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();
}
于 2012-05-17T12:54:22.970 回答