3

我在 asp.net mvc 3 中有一个小项目,我正在使用 RavenDB 存储数据。但是当我尝试更新实体时,我有错误提示“尝试将不同的对象与 id 'orders/257 ' 相关联”我有一个服务类来管理实体。

这是更新名为 Order 的实体的方法。为了清楚起见,我省略了其余的方法

  public ErrorState UpdateOrder(Order order)
    {
        try
        {
            documentSession.Store(order);
            documentSession.SaveChanges();
            return new ErrorState { Success = true };

        }
        catch (Exception ex)
        {
            return new ErrorState { Success = false, ExceptionMessage = ex.Message };

        }
    }

这是 OrderRepository 的其余部分

  private readonly IDocumentSession documentSession;

public OrderRepository(IDocumentSession _documentSession)
{
    documentSession = _documentSession;
}

ErrorState 类用于管理应用程序中的错误,它包含布尔成功和异常字符串消息。

这是我的编辑操作。

 public ActionResult Edit(int id)
        {
            Order order = orderRepository.ObtainOrder(id);
            if (order == null)
            {
                TempData["message"] = string.Format("Order no: {0} not found", id);
                return RedirectToAction("Index");
            }
            return View(order);

        }



        [HttpPost]
        public ActionResult Edit(Order order)
        {
            if(!ModelState.IsValid)
                return View();

            errorState = orderRepository.UpdateOrder(order);
            if (errorState.Success)
            {
                TempData["message"] = string.Format("Order no: {0} has been changed", order.Id);
                return RedirectToAction("Index");
            }
            else
            {
                TempData["Message"] = string.Format("Error on update order no: {0} MSG: {1}", order.Id,errorState.ExceptionMessage);
                return RedirectToAction("Index");
            }


        }

这是控制器的其余部分,为了清楚起见,我省略了其余的操作。

private readonly IOrderRepository orderRepository;
private ErrorState errorState;

public HomeController(IOrderRepository _orderRepository,IDocumentSession _documentSession)
{
    orderRepository = _orderRepository;

} 
4

1 回答 1

1

您已经有一个具有该 ID 的订单实例。检查会话生命周期,是否有可能跨请求具有相同的会话?

于 2012-11-06T18:59:10.070 回答