RavenDB - save or update entity, changed outside the session

Viewed 191

While getting familiar with RavenDb I've stumbled into one important question - is it possible to open session, load document, then close session, edit previously loaded document, open another session and update document in the database?

All examples provided in documentation demonstrates document's editing inside one single session only. Also I am aware about patch operations, but both scenarios does not fit my demands.

Maybe there is something resembling EF's SaveOrApdate() or another mechanism I don't know yet?

Thanks.

1 Answers

No problem. You can open a session, save a document & close the session.
After that, you can open another session, load the document that you saved, edit it, and save it again.

Company newCompany = new Company
{
    Name = companyName,
    Phone = companyPhone
};

// Open a session and save a new document
using (IDocumentSession session = DocumentStoreHolder.Store.OpenSession())
{
    session.Store(newCompany); 
    // The new document ID is immediately available, save it for later usage                  
    theNewDocumentId = newCompany.Id;                    
    session.SaveChanges();
}

// Open a session, Load the document, edit & save 
using (IDocumentSession session = DocumentStoreHolder.Store.OpenSession())
{
    Company company = session.Load<Company>(theNewDocumentId );                
    company.Name = companyName;                
    session.SaveChanges();
}

See explanation about the new document ID that is generated in:
https://demo.ravendb.net/demos/csharp/basics/create-document#step-3

Related