Bulk Insert Attachments


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

  • In this page:

Usage flow

  • Create a BulkInsert instance.

  • Pass the Document ID to the instance's AttachmentsFor method.

  • To add an attachment, call Store.
    Pass it the attachment's name, stream, and type (optional).
    The Store function can be called repeatedly as necessary.

  • Note:
    If an attachment with the specified name already exists on the document,
    the bulk insert operation will overwrite it.

Usage example

In this example, we attach a file to all User documents that match a query.

List<User> users;

// Choose user profiles for which to attach a file
using (var session = store.OpenSession())
{
    users = session.Query<User>()
        .Where(u => u.Age < 30)
        .ToList();
}

// Prepare content to attach
byte[] byteArray = Encoding.UTF8.GetBytes("some contents here");
var stream = new MemoryStream(byteArray);

// Create a BulkInsert instance
using (var bulkInsert = store.BulkInsert())
{
    for (var i = 0; i < users.Count; i++)
    {
        string userId = users[i].Id;
        
        // Call 'AttachmentsFor', pass the document ID for which to attach the file
        var attachmentsBulkInsert = bulkInsert.AttachmentsFor(userId);

        // Call 'Store' to add the file to the BulkInsert instance
        // The data stored in bulkInsert will be streamed to the server in batches 
        attachmentsBulkInsert.Store("AttachmentName", stream);
    }
}
public class User
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string LastName { get; set; }
    public string AddressId { get; set; }
    public int Count { get; set; }
    public int Age { get; set; }
}

Syntax

public AttachmentsBulkInsert AttachmentsFor(string id)
Parameter Type Description
id string The document ID to which the attachment should be added.

public void Store(string name, Stream stream, string contentType = null)
Parameter Type Description
name string Name of attachment
stream Stream The attachment's stream
contentType string Type of attachment (default: null)