Reputation: 370
I cannot get OnBeforeStore to fire using a BulkInsert.
It fires fine during a regular Store operation.
I'm trying to use an Invoice number generator to add a formatted number and I'd like to do that in OnBeforeStore.
See code example:
static async Task GenerateInvoiceTest()
{
using var store = new DocumentStore
{
Urls = new string[] { "https://localhost:8080" },
Database = "APC",
};
//this never fires using BulkInsert
store.OnBeforeStore += (s, e) =>
{
if (!(e.Entity is Invoice invoice)) return;
if (invoice.InvoiceNumber != 0) return;
invoice.InvoiceNumber = new Random().Next(1, 1000);
};
store.Initialize();
//sample invoices
var invoices = new List<Invoice>
{
new Invoice { StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(3) },
new Invoice { StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(3) },
};
//bulk insert test
using var session = store.OpenAsyncSession();
using var bulkInsert = store.BulkInsert();
invoices.ForEach(i => bulkInsert.Store(i));
//this does NOT fire OnBeforeStore
await session.SaveChangesAsync();
foreach (var invoice in invoices)
{
//always prints 0
Console.WriteLine(invoice.InvoiceNumber);
}
//regular test
var otherInvoice = new Invoice { StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(3) };
await session.StoreAsync(otherInvoice);
//this DOES fire OnBeforeStore
await session.SaveChangesAsync();
}
Upvotes: 4
Views: 72
Reputation: 3839
OnBeforeStore
is invoked as part of the Session SaveChanges
method
See this documentation about OnBeforeStore
http://localhost:54391/docs/article-page/5.0/Csharp/client-api/session/how-to/subscribe-to-events
The event takes argument BeforeStoreEventArgs
that consists of the Session entity's ID and the entity itself.
You define OnBeforeStore
on the 'Store' but it is Not for use with bulkInsert.
It is for when saving from a Session.
BulkInsert operates on the Store itself, not on the Session
Upvotes: 3