1

我正在使用 RavenDB 4.0.6 的 BulkInsert 操作插入一堆产品:

    using (var bulk = Store.BulkInsert())
    {
        foreach (var p in products)
        {
            p.Id = string.Empty; // <-- notice this
            await bulk.StoreAsync(p);
        }
    }

请注意,我通过显式提供string.EmptyId 属性的值来故意跳过标识符创建策略。这是基于 RavenDB 文档的Autogenerated ID's 部分

运行代码时出现错误:

System.InvalidOperationException:文档 ID 必须具有非空值

由 BulkInsertOperation.cs 中的此代码片段直接生成

我的问题是如何防止此错误并仍保持与其他代码相同的 ID 生成策略?

例如,我从不将 Id 属性设置为string.Empty. 而且我担心将其设置为例如Guid.NewGuid.ToString()可能会导致其他问题(也请参阅此问题)。

4

1 回答 1

2

对于批量操作,您必须将 Id 属性保留为空(非空字符串)以使其自动生成顺序 ID,或者手动生成 Guid ID。

API 在批量插入和会话插入之间有点不一致:

using (var store = new DocumentStore() { Urls = new[] { "http://localhost:8080" } }.Initialize())
{
  using (var bulk = store.BulkInsert("Sample"))
  {
    bulk.Store(new SampleDocument { Name = "Bulk.Store Null Id", Id = null }); // Sequential Id (I.E. SampleDocuments/1-A)
    bulk.Store(new SampleDocument { Name = "Bulk.Store Blank Id", Id = "" }); // Throws Error
    bulk.Store(new SampleDocument { Name = "Bulk.Store Guid Id", Id = Guid.NewGuid().ToString() }); // Guid Id
  }

  using (var session = store.OpenSession("Sample"))
  {
    session.Store(new SampleDocument { Name = "Session.Store Null Id", Id = null }); // Sequential Id (I.E. SampleDocuments/2-A)
    session.Store(new SampleDocument { Name = "Session.Store Empty Id", Id = "" }); // Guid Id
    session.Store(new SampleDocument { Name = "Session.Store Guid Id", Id = Guid.NewGuid().ToString() }); // Guid Id
    session.SaveChanges();
  }
}
于 2018-09-26T14:03:31.180 回答