Bulk Insert: How to Add Attachments


  • store.BulkInsert is RavenDB's high-performance data insertion operation.
    Use its AttachmentsFor interface's Store method to add attachments with great speed.

  • In this page:

Syntax

  • AttachmentsFor

    public AttachmentsBulkInsert AttachmentsFor(string id)
    Parameters Type Description
    id string Document ID
  • AttachmentsFor.Store

    public void Store(string name, Stream stream, string contentType = null)
    Parameters Type Description
    name string Attachment Name
    stream Stream Attachment Stream
    contentType string Attachment Type (default: null)

Usage Flow

  • Create a store.BulkInsert instance.
  • Pass the instance's AttachmentsFor interface -
    • Document ID
  • Call Store as many times as you like. Pass it -
    • The attachment Name, Stream, and Type

Usage Sample

  • In this sample, we attach a file to all User documents.
    List<User> result;
    
    // Choose user profiles to attach files to
    using (var session = store.OpenSession())
    {
        IRavenQueryable<User> query = session.Query<User>()
            .Where(u => u.Age < 30);
    
        result = query.ToList();
    }
    
    // Bulk-insert an attachment to the chosen users
    using (var bulkInsert = store.BulkInsert())
    {
        for (var user = 0; user < result.Count; user++)
        {
            byte[] byteArray = Encoding.UTF8.GetBytes("some contents here");
            var stream = new MemoryStream(byteArray);
    
            string userId = result[user].Id;
            
            // Choose the document to attach to
            var attachmentsFor = bulkInsert.AttachmentsFor(userId);
    
            // Attach the stream
            await attachmentsFor.StoreAsync("attName", stream);
        }
    }