Attachments: Storing Attachments

In order to store an attachment in RavenDB you need to create a document. Then you can attach an attachment to the document using the session.Advanced.Attachments.Store method.

Attachments, just like documents, are a part of the session and will be only saved on the Server when DocumentSession.SaveChanges is executed (you can read more about saving changes in session here).

Syntax

Attachments can be stored using one of the following session.Advanced.Attachments.Store methods:

void Store(string documentId, string name, Stream stream, string contentType = null);
void Store(object entity, string name, Stream stream, string contentType = null);

Example

using (var session = store.OpenSession())
using (var file1 = File.Open("001.jpg", FileMode.Open))
using (var file2 = File.Open("002.jpg", FileMode.Open))
using (var file3 = File.Open("003.jpg", FileMode.Open))
using (var file4 = File.Open("004.mp4", FileMode.Open))
{
    var album = new Album
    {
        Name = "Holidays",
        Description = "Holidays travel pictures of the all family",
        Tags = new[] { "Holidays Travel", "All Family" },
    };
    session.Store(album, "albums/1");

    session.Advanced.Attachments.Store("albums/1", "001.jpg", file1, "image/jpeg");
    session.Advanced.Attachments.Store("albums/1", "002.jpg", file2, "image/jpeg");
    session.Advanced.Attachments.Store("albums/1", "003.jpg", file3, "image/jpeg");
    session.Advanced.Attachments.Store("albums/1", "004.mp4", file4, "video/mp4");

    session.SaveChanges();
}
using (var asyncSession = store.OpenAsyncSession())
using (var file1 = File.Open("001.jpg", FileMode.Open))
using (var file2 = File.Open("002.jpg", FileMode.Open))
using (var file3 = File.Open("003.jpg", FileMode.Open))
using (var file4 = File.Open("004.mp4", FileMode.Open))
{
    var album = new Album
    {
        Name = "Holidays",
        Description = "Holidays travel pictures of the all family",
        Tags = new[] { "Holidays Travel", "All Family" },
    };
    await asyncSession.StoreAsync(album, "albums/1");

    asyncSession.Advanced.Attachments.Store("albums/1", "001.jpg", file1, "image/jpeg");
    asyncSession.Advanced.Attachments.Store("albums/1", "002.jpg", file2, "image/jpeg");
    asyncSession.Advanced.Attachments.Store("albums/1", "003.jpg", file3, "image/jpeg");
    asyncSession.Advanced.Attachments.Store("albums/1", "004.mp4", file4, "video/mp4");

    await asyncSession.SaveChangesAsync();
}