【问题标题】:BulkInsert error with RavenDB: Document id must have a non empty valueRavenDB 的 BulkInsert 错误:文档 ID 必须具有非空值
【发布时间】:2018-09-26 22:03:31
【问题描述】:

我正在使用 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.Empty 作为 Id 属性的值来故意跳过标识符创建策略。这是基于 RavenDB 文档section Autogenerated ID's

运行代码时出现错误:

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

这是由BulkInsertOperation.cs中的这个coden-p直接产生的。

我的问题是我怎样才能防止这个错误并且仍然保持与我的其他代码相同的 ID 生成策略?

例如我从未将 Id 属性设置为 string.Empty 以外的任何值。而且我担心将其设置为例如Guid.NewGuid.ToString() 可能会导致其他问题(也请参阅this question)。

【问题讨论】:

    标签: c# ravendb ravendb4


    【解决方案1】:

    对于批量操作,您必须将 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();
      }
    }
    

    【讨论】:

    • 谢谢,这确实证实了我所说的。但是Guid.NewGuid().ToString() 似乎确实与依赖string.Empty 有不同的副作用,另请参阅我问题末尾的链接问题。这又回到了我的实际问题:可以做些什么来防止这种情况并保持相同的身份策略?
    • 我认为核心问题是对于 Load,类型安全只在会话中持续存在。看来,无论 Id 策略如何,一旦关闭会话,就会失去类型安全性。
    • 根据stackoverflow.com/a/49922425/4541880store.Query&lt;T&gt;.Where(x =&gt; x.Id == id) 应该是高性能和类型安全的,无论 Id 策略如何
    猜你喜欢
    • 2013-05-07
    • 2018-09-20
    • 2021-03-06
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 2018-06-01
    • 2012-07-08
    • 2018-04-01
    相关资源
    最近更新 更多