为了账号安全,请及时绑定邮箱和手机立即绑定

插入时出现 ASP.Net MVC 重复键异常

插入时出现 ASP.Net MVC 重复键异常

C#
温温酱 2022-11-22 16:16:15
尝试将订单插入数据库时出现奇怪的重复键异常。订单具有将用户与订单联系起来的用户关系。我不确定为什么会发生重复异常,因为我从数据库中获取用户,然后在插入之前将其分配给订单。我的用户上下文只是用户的 IRepository。信息使用 EF 版本 6.2.0Ctorpublic OrderManagerController(IRepository<Order> orderContext,        IRepository<User> userContext){    _orderContext = orderContext;     userContext = userContext;}注入绑定private static IKernel CreateKernel(){    var kernel = new StandardKernel();    try    {        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();        //Bind concrete classes to contracts        kernel.Bind<IRepository<Order>>().To<SQLRepository<Order>>();        kernel.Bind<IRepository<User>>().To<SQLRepository<User>>();        RegisterServices(kernel);        return kernel;    }    catch    {        kernel.Dispose();        throw;    }}行动[HttpPost]    public ActionResult Create(OrderManagerViewModel order)    {        if (!ModelState.IsValid)            return View("Create", order);        else        {            User user = _userContext.Find(order.AssignedUserId); // Grab user from DB            //Create the order from the passed in view model and DB user            Order orderToInsert = new Order            {                AssignedUser = user,                Category = order.Category,                Comments = order.Comments,                CustomerName = order.CustomerName,                EstimatedHours = order.EstimatedHours,                SalesOrderNumber = order.SalesOrderNumber,                LineType = order.LineType,                OrderTotal = order.OrderTotal,                ScheduledCompletionDate = order.ScheduledCompletionDate,                OutDate = order.OutDate            };            _orderContext.Insert(orderToInsert); // Insert            _orderContext.Commit();//Save -----Crashes with Duplicate Exception on AssignedUser.Id            return RedirectToAction("Index");        }    }OrderManagerViewModel
查看完整描述

1 回答

?
小怪兽爱吃肉

TA贡献1852条经验 获得超1个赞

看起来问题是因为您的 User 和 Order 来自不同的上下文...我看不到您在 ninject 中注册 DbContext 的位置,但您想确保在 request scope中注册它。这将确保您在单个请求中获得所有操作的相同上下文。



查看完整回答
反对 回复 2022-11-22
  • 1 回答
  • 0 关注
  • 86 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信