I just discovered Marten today and currently trying to learn on how to use this properly.
For creating new records, it can be as straight forward as providing a blank form/view then during submission - just open a new session then perform the saving like this:
using (var session = _documentStore.LightweightSession())
{
session.Store(model);
session.SaveChanges();
}
But how about the updating existing records? After fetching the record and displaying it on the form, is it fine to just use the same code as I used above or is there another way? The only example I found for updating is loading the record from session by calling Load() method then editing the properties, after that is calling the SaveChanges() method of the session used.
Marten tracks documents using the document identity
. The Id can be either a public field or property, and the name must be either id
or Id
or ID
.
Quote from the doc
:
Marten's .Net API makes no distinctions between inserts and updates. The Postgresql functions generated by Marten to update the document storage tables perform "upserts" for you. Anytime a document is registered through IDocumentSession.Store(document), Marten runs the "auto-assignment" policy for the id type of that document. See Document Identity for more information on document id's.
This means that you don't necessarily need to load a document before updating it. If you know its identity value, you could simply change some property on the document and call IDocumentSession.Store(document)
which will perform an update if a document with this id already exists in the datastore.