【问题标题】:SqlException occures after changing Column properties in asp.net mvc 3在 asp.net mvc 3 中更改 Column 属性后发生 SqlException
【发布时间】:2013-02-06 12:45:12
【问题描述】:

我有以下模型:项目包含产品、运输、用户 ID(创建此产品)。 “Item : Product”和“Item : Shipping”是“1:1”的关系)。当我想向数据库添加新产品时,会发生 SqlException:

无法将值 NULL 插入到列 'ProductId'、表 'C:\USERS\ALEKSEY\REPOS\WORKING-COPY\WEBSTORE\WEBSTORE\APP_DATA\WEBSTORE.MDF.dbo.Products';列不允许空值。插入失败。

在我将“ProductId”列的“Is Identity”属性从 true 更改为 false 之前,一切正常,因此不再自动生成。我这样做是因为我需要从 xml 文件上传数据(并将该文件的 ID 保存在 ProductId 中)。我还需要用户添加新产品的能力。

这是创建新产品、运输和相应商品的控制器操作方法:

public ViewResult Create()
    {
        var productId = 0;
        for (var i = 0; i < Int32.MaxValue; i++)
        {
            if (_productRepository.GetProduct(i) == null)
                productId = i;
        }    
        // the same code as above to get shippingId

        var p = _productRepository.CreateProduct(productId, "", "", 0, "", "", "");
        var s = _shippingRepository.CreateShipping(shippingId, 0, "");
        var userId = (Guid)Membership.GetUser().ProviderUserKey;
        var model = new StoreEditViewModel(_productRepository)
        {
            CurrentItem = _itemsRepository.CreateItem(p.ProductId, s.ShippingId, userId, DateTime.Now),
        };
        return View("Edit", model);
    }

如果我在产品创建行中添加注释,运输也会发生同样的异常。

这是使用 Linq To SQL 创建新产品的 ProductRepository 方法:

public Product CreateProduct(int productId, string name, /* other properties */)
    {
        var product = new Product
        {
            ProductId = productId,
            Name = name,
            // other properties
        };
        _dataContext.Products.InsertOnSubmit(product);
        _dataContext.SubmitChanges(); // SqlException occures !
        return product;
    }   

我该如何解决这个问题?

编辑 1: 我还尝试在 CreateProduct(100, other stuff) 方法中插入整数而不是 productId。还是得到 SqlException:

无法将值 NULL 插入到列“ProductId”、表“WebStore.dbo.Products”中;列不允许空值。插入失败。 声明已终止。

编辑 2: _dataContext 似乎不知道更改后的 Columns 的属性(因为 @devio 支持)。我只需要更新 MyAppDataContext 类。

这个问题实际上已经回答了,但我还有另一个问题: 现在,当我调用 Create() 方法 Product、Shipping 和 Item 条目被添加到相应的表中。比 Create() 方法返回“编辑”视图,您可以在其中填充实际数据(在创建新项目时它是空的)。

“编辑”视图中的表单应该由 Edit() 操作方法处理:

    [HttpPost]
    public ActionResult Edit(StoreEditViewModel model, HttpPostedFileBase image)
    {
        var p = model.CurrentItem.Product;
        var s = model.CurrentItem.Shipping;
        if (ModelState.IsValid)
        {
            if (image != null)
            {
                var path = AppDomain.CurrentDomain.BaseDirectory +
                          ConfigurationManager.AppSettings["product-images-directory"];
                var imageName = "prod-" + p.ProductId.ToString(CultureInfo.InvariantCulture) + ".jpg";
                image.SaveAs(path + imageName);
            }
            _productRepository.UpdateProduct(p);
            _shippingRepository.UpdateShipping(s);
            return RedirectToAction("Content");
        }
        return View("Edit", model);
    }

我得到(我自己的翻译)“应用程序中的服务器错误”,堆栈跟踪:

[MissingMethodException: No parameterless constructor defined for this object.]


System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
System.Activator.CreateInstance(Type type) +6
System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +183
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +564
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +411
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +317
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +117
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +324
System.Web.Mvc.Controller.ExecuteCore() +106
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +91
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +34
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +19
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +48
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9629708
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

我真的不知道如何处理这个奇怪的堆栈跟踪,找不到任何友好的行。

可能是什么原因?

【问题讨论】:

  • 您传递给CreateProductproductId 为空。如果 productId 为空,请使用条件不要插入 Product 表,因为您知道 pk 列不允许空值
  • 我也尝试将像“1000”这样的整数值传递给 CreateProduct 方法——同样的例外!
  • 试试这样:Product pr=new Product{ ProductId=1000, // and some others}; context.Products.Add(pr); context.SaveChanges();
  • 我使用 Linq To SQL 将数据插入数据库。似乎没有方法 Add(pr) 和 SaveChanges()。浏览我最后的代码sn-p
  • _dataContext“知道”您更改了 Identity 属性吗?

标签: asp.net sql database asp.net-mvc-3 linq-to-sql


【解决方案1】:

正如我已经在编辑 2 中所写:似乎 _dataContext 不知道更改后的 Columns 的属性(正如 @devio 支持的那样)。我只需要更新 MyAppDataContext 类。

发生 MissingMethodException 是因为 StoreEditViewModel 没有无参数构造函数,所以我添加了空构造函数,一切都开始工作了!

StoreEditViewModel 需要 DefaultModelBinder 的无参数构造函数来实例化它。

【讨论】:

    猜你喜欢
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多