问题描述
在熟悉 RavenDb 时,我偶然发现了一个重要问题 - 是否可以打开会话、加载文档、然后关闭会话、编辑先前加载的文档、打开另一个会话并更新数据库中的文档?
文档中提供的所有示例仅演示了单个会话中的文档编辑。我也知道补丁操作,但这两种情况都不符合我的要求。
也许有一些类似于 EF 的 SaveOrApdate() 或其他我还不知道的机制?
谢谢。
解决方法
没问题。
您可以打开会话、保存文档和关闭会话。
之后,您可以打开另一个会话,加载您保存的文档,对其进行编辑,然后再次保存。
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();
}
查看关于生成的新文档ID的说明:
https://demo.ravendb.net/demos/csharp/basics/create-document#step-3