Update Entities


  • To modify existing documents:

    • Retrieve documents from the database using Load or by a Query.
      The entities loaded from the documents are added to the internal entities map that the Session manages.

    • Edit the properties you wish to change.
      The session will track all changes made to the loaded entities.

    • Save to apply the changes.
      Once SaveChanges() returns it is guaranteed that the data is persisted in the database.

  • In this page:


Load a document & update

  • In this example we Load a company document and update its PostalCode property.

using (var session = store.OpenSession())
{
    // Load a company document
    // The entity loaded from the document will be added to the Session's entities map
    Company company = session.Load<Company>("companies/1-A");

    // Update the company's PostalCode
    company.Address.PostalCode = "TheNewPostalCode";

    // Apply changes
    session.SaveChanges();
}
using (var asyncSession = store.OpenAsyncSession())
{
    // Load a document
    // The entity loaded from the document will be added to the Session's entities map
    Company company = await asyncSession.LoadAsync<Company>("companies/KitchenAppliances");

    // Update the company's PostalCode
    company.Address.PostalCode = "TheNewPostalCode";

    // Apply changes
    await asyncSession.SaveChangesAsync();
}

Query for documents & update

  • In this example we Query for company documents whose PostalCode property is 12345,
    and modify this property for the matching documents.

using (var session = store.OpenSession())
{
    // Query: find companies with the specified PostalCode
    // The entities loaded from the matching documents will be added to the Session's entities map
    IRavenQueryable<Company> query = session.Query<Company>()
        .Where(c => c.Address.PostalCode == "12345");

    var matchingCompanies = query.ToList();

    // Update the PostalCode for the resulting company documents
    for (var i = 0; i < matchingCompanies.Count; i++)
    {
        matchingCompanies[i].Address.PostalCode = "TheNewPostalCode";
    }

    // Apply changes
    session.SaveChanges();
}
using (var asyncSession = store.OpenAsyncSession())
{
    // Query: find companies with the specified PostalCode
    // The entities loaded from the matching documents will be added to the Session's entities map
    IRavenQueryable<Company> query = asyncSession.Query<Company>()
        .Where(c => c.Address.PostalCode == "12345");

    var matchingCompanies = await query.ToListAsync();

    // Update the PostalCode for the resulting company documents
    for (var i = 0; i < matchingCompanies.Count; i++)
    {
        matchingCompanies[i].Address.PostalCode = "TheNewPostalCode";
    }

    // Apply changes
    await asyncSession.SaveChangesAsync();
}