代码之家  ›  专栏  ›  技术社区  ›  Alfred Wallace

我需要多久保存一次上下文?

  •  1
  • Alfred Wallace  · 技术社区  · 8 年前

    在存储库中,我将执行以下两个连续任务:

    // Update vendorOrder
    vendorOrder.VendorOrderStatus = VendorOrderStatus.Completed;
    vendorOrderRepository.UpdateVendorOrder(vendorOrder);
    vendorOrderRepository.Save();
    // Update order
    order.OrderStatus = OrderStatus.Completed;
    orderRepository.UpdateOrder(order);
    orderRepository.Save();
    

    两者 vendorOrderRepository orderRepositoryrepositorty 有自己的 Save() 方法:

    public void Save()
    {
        context.SaveChanges();
    }
    
    • 威尔打电话来 在每个存储库中,只保存对 上下文,或者它将保存对上下文所做的每一个更改

    • 在我的例子中,调用 两次?我只要打电话就行了吗 保存() 最后呢?

    (我可以试着看看什么有效,但如果可能的话,我想根据MVC的工作原理给出一个明确的答案,以防出现异常情况。这可能是对MVC的基本理解,但我跳过了这一部分……)

    供应商订单存管开始于:

    public class VendorOrderRepository : IVendorOrderRepository, IDisposable
    {
        private ApplicationDbContext context = new ApplicationDbContext();
        private IOrderRepository orderRepository;
        public VendorOrderRepository(ApplicationDbContext context)
        {
            this.context = context;
            orderRepository = new OrderRepository(context);
        }
    

    orderRepository开始于:

    public class OrderRepository : IOrderRepository, IDisposable
    {
        private ApplicationDbContext context = new ApplicationDbContext();
        private IVendorOrderRepository vendorOrderRepository;
        public OrderRepository(ApplicationDbContext context)
        {
            this.context = context;
            vendorOrderRepository = new VendorOrderRepository(context);
        }
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   Travis J    8 年前

    我需要多久保存一次上下文?

    经常这么做是有道理的。通常,您只想调用一次SaveChanges,除非处理大型集,在这种情况下,使用事务并成批保存是有意义的。

    在每个存储库中调用Save()只会保存对该存储库中上下文的更改,还是会保存到那时为止对任何其他存储库中上下文所做的每个更改?

    “那里的背景”有点模糊。调用SaveChanges将保存 全部的 vendorOrderRepository 和 orderRepository 共享相同的上下文,然后调用一次将保存所做的每个更改。

    在我的示例中,调用Save()两次是否多余?如果我在最后调用Save()它会工作吗?

    如果他们使用相同的上下文,那么是的。如果不一样,那就不多余了。


    从更广泛的意义上讲,SaveChanges的工作方式是保存存储在变更跟踪器中的实体(请参见 ChangeTracker Class MDN 有关详细信息)。更改跟踪程序(可通过 context.ChangeTracker ),除其他外,包含一组它跟踪的实体。这些将是在保存更改期间更新的实体,从技术上讲,这些实体被称为“附加的”。

    通过迭代可以看到按类型附加的实体列表 context.ChangeTracker.Entries<T>() T 是你喜欢的类型。

        2
  •  -1
  •   Shyam Bhagat    8 年前

    这取决于你使用的是什么样的设计模式。如果您使用的是Repository模式,则上下文将在所有存储库中共享,并且相同的上下文将跟踪所有实体中的更改。所以,只要调用Save()或context.SaveChanges()一次就可以了。