【问题标题】:RavenDB : How can I Savechanges only for specific objectsRavenDB:如何仅针对特定对象保存更改
【发布时间】:2013-03-28 00:07:56
【问题描述】:

在 MVC 应用程序中,对于请求,我创建一个文档会话并检索一堆对象并在内存中处理它们。在此期间如果出现错误,我会创建一个 Error 对象并将其存储在 Raven 中。当我调用 SaveChanges 来存储这个 Error 对象时,内存中所有其他对象的状态也会被保存。我需要避免这种情况。如何仅为 Error 对象触发 Savechanges? 我们使用 StructureMap 来获取 DocumentSession 的实例:

public RavenDbRegistry(string connectionStringName)
{
    For<IDocumentStore>()
        .Singleton()
        .Use(x =>
        {
            var documentStore = new DocumentStore { ConnectionStringName = connectionStringName };
            documentStore.Initialize();         
            return documentStore;
        }
        )
        .Named("RavenDB Document Store.");
    For<IDocumentSession>()
        .HttpContextScoped()
        .Use(x =>
        {
            var documentStore = x.GetInstance<IDocumentStore>();
            return documentStore.OpenSession();
        })
        .Named("RavenDb Session -> per Http Request.");
}

这就是我保存错误对象的方式:

private void SaveError(Error error)
{
    documentSession.Store(error);
    documentSession.SaveChanges();
}

我尝试过的几个变体没有按预期工作: 1. 创建一个新的 DocumentSession 仅用于错误记录:

private void SaveError(Error error)
{
    var documentStore = new DocumentStore { ConnectionStringName = "RavenDB" };
    documentStore.Initialize();
    using (var session = documentStore.OpenSession())
    {
        documentSession.Store(error);
        documentSession.SaveChanges();
    }
}

2。在 TransactionScope 中包装

private void SaveError(Error error)
{
    using (var tx = new TransactionScope())
    {
        documentSession.Store(error);
        documentSession.SaveChanges();
        tx.Complete();
    }
}

目前我不确定该怎么做。任何帮助将不胜感激。

********更新 ************

我能够通过在 SaveChanges 之前添加以下行来解决问题

documentSession.Advanced.Clear();.

所以现在我的 SaveError 看起来像这样:

private void SaveError(Models.CMSError error)
        {
            documentSession.Advanced.Clear();
            documentSession.Store(error);
            documentSession.SaveChanges();            
        }

【问题讨论】:

    标签: ravendb


    【解决方案1】:

    创建一个新的文档会话 - 但在现有的文档存储中,而不是在新的。

    注入一个IDocumentStore 并在上面调用OpenSession

    【讨论】:

    • 感谢您的回复。我仍然必须尝试您的解决方案。目前我在帖子中提到的改变对我有用。
    【解决方案2】:

    我能够通过在 SaveChanges 之前添加以下行来解决问题

    documentSession.Advanced.Clear();.
    

    所以现在我的 SaveError 看起来像这样:

    private void SaveError(Models.CMSError error)
            {
                documentSession.Advanced.Clear();
                documentSession.Store(error);
                documentSession.SaveChanges();            
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-07
      • 2016-08-24
      • 1970-01-01
      • 1970-01-01
      • 2020-02-07
      • 2013-02-13
      相关资源
      最近更新 更多