ASP.NET MVC/Core 使用 Marten 的正确方法

Proper way of using Marten for ASP.NET MVC/Core

我今天才发现 Marten,目前正在努力学习如何正确使用它。

要创建新记录,可以像提供空白一样直接 form/view 然后在提交过程中 - 只需打开一个新会话然后像这样执行保存:

using (var session = _documentStore.LightweightSession())
        {
            session.Store(model);
            session.SaveChanges();                
        }

但是更新现有记录呢?获取记录并将其显示在表单上后,是否可以只使用与我上面使用的代码相同的代码,还是有其他方法?我发现的唯一更新示例是通过调用 Load() 方法从会话加载记录,然后编辑属性,之后调用所用会话的 SaveChanges() 方法。

Marten 使用 document identity 跟踪文档。 Id 可以是 public 字段或 属性,名称必须是 idIdID.

引自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.

这意味着您不一定需要在更新文档之前加载它。如果您知道它的标识值,您可以简单地更改文档上的一些 属性 并调用 IDocumentSession.Store(document) 如果数据存储中已存在具有此 ID 的文档,它将执行更新。