using Raven.Client.Documents;
using Raven.Client.Documents.Operations;
using Raven.Client.Documents.Queries;
using System.Threading.Tasks;
using System.Collections.Generic;
private const string TestDBName = "Hogwarts";
private static DocumentStore Store { get; set; }
public static async Task Main()
Store = new DocumentStore {
Urls = new[]{"http://live-test.ravendb.net"}
await Truncate("Contacts");
var contacts = await MockData();
await ExampleThatWorks(contacts.Item1.Id);
await ExampleThatDoesntWork(contacts.Item2.Id);
private static async Task ExampleThatWorks(string contactId)
var attachments = new List<Attachment>
new Attachment{ Id = Guid.NewGuid().ToString(), Name = "First.txt" },
new Attachment{ Id = Guid.NewGuid().ToString(), Name = "Second.txt" }
foreach(var attachment in attachments)
await AddAttachment(contactId, attachment);
private static async Task ExampleThatDoesntWork(string contactId)
var attachments = new List<Attachment>
new Attachment{ Id = Guid.NewGuid().ToString(), Name = "First.txt" },
new Attachment{ Id = Guid.NewGuid().ToString(), Name = "Second.txt" }
var tasks = attachments.Select(x => AddAttachment(contactId, x)).ToList();
await Task.WhenAll(tasks);
private static async Task AddAttachment(string contactId, Attachment attachment)
using (var session = Store.OpenAsyncSession())
var contact = await session.LoadAsync<Contact>(contactId);
contact.Attachments.Add(attachment);
await session.StoreAsync(contact);
await session.SaveChangesAsync();
private static async Task Truncate(string collectionName)
var queryToDelete = new IndexQuery {Query = $"FROM {collectionName}",};
var operation = await Store.Operations.ForDatabase(TestDBName).SendAsync(
new DeleteByQueryOperation(
new QueryOperationOptions {
await operation.WaitForCompletionAsync(TimeSpan.FromSeconds(60));
private static async Task<Tuple<Contact,Contact>> MockData()
using (var session = Store.OpenAsyncSession())
Id = Guid.NewGuid().ToString(),
DisplayName = "Harry Potter"
var hermione = new Contact
Id = Guid.NewGuid().ToString(),
DisplayName = "Hermione Granger"
await session.StoreAsync(harry);
await session.StoreAsync(hermione);
await session.SaveChangesAsync();
return new Tuple<Contact, Contact>(harry, hermione);
public string Id { get; set; }
public string Workspace { get; set; }
public string DisplayName { get; set; }
public List<Attachment> Attachments { get; set; } = new List<Attachment>();
public string Id { get; set; }
public string Name { get; set; }