【问题标题】:Cannot insert the value NULL into column 'ProductId', table 'ProductDB.dbo.Brand';无法将值 NULL 插入列“ProductId”、表“ProductDB.dbo.Brand”;
【发布时间】:2017-10-04 19:17:38
【问题描述】:

我有两张桌子,即。 tblProduct 和 Brands,tblProduct 包含: ProductId、ProductName、数量、价格、Entry_Date。 Brands 包含:ProductId、BrandID、BrandName、BrandDescription、DietType、ProductId(来自 tbProduct 的 FK)。

我正在使用 LINQ,并希望在单击按钮时将此数据插入到两个表中,这是插入方法:

protected void BtnAdd_Click(object sender, EventArgs e)
{
    tblProduct products = new tblProduct();

    using (ProductDataContext context = new ProductDataContext())
    {
        try
        {
            tblProduct prod = new tblProduct();
            {
                prod.ProductName = TxtProductName.Text;
                prod.Quantity = Int32.Parse(TxtQuantity.Text);
                prod.Price = Int32.Parse(TxtPrice.Text);
                prod.Entry_Date = DateTime.Parse(TxtDate.Text);
            };
            context.tblProducts.InsertOnSubmit(prod);
            context.SubmitChanges();

            Label2.Text = "Product Inserted";

            Brand br = new Brand();
            {
                br.BrandName = TxtBrandName.Text;
                br.BrandDescription = TxtBrandDescription.Text;
                br.DietType = TxtDietType.Text;
            };

            prod.Brands.Add(br);
            context.Brands.InsertOnSubmit(br);
            context.SubmitChanges();
            Label1.Text = "Done";
        }
        catch (Exception exe)
        {
            Label1.Text = exe.Message;
        }
    }
}

我正在尝试在两个表上插入,但插入命令仅适用于第一个表 (tblProducts),但不会在 Brands 表中插入任何内容,我不确定这里似乎是什么问题。 请注意,BrandID 和 ProductId(在两个表上)都设置为自动递增。

【问题讨论】:

  • brand表对product表的外键是否有约束?如果是这样,您需要在插入到品牌表中时包含已插入到产品表中的产品 ID
  • @RH6 感谢您尽早回复,是的,ProductId 是 Brands 表上的外键,我也将其设置为自动递增。你是说我应该包含类似 prod.ProductId = br.ProductId 的东西吗?
  • 您需要从之前插入的产品表中检索主键(productID),然后在插入品牌表时,外键必须与此匹配,假设它们是 1 到1. 编辑:基本上就是我刚刚发布的答案所说的
  • Brand 也应该有一个属性Product。使用它代替ProductId 并调用SubmitChanges 一次。

标签: c# sql sql-server linq


【解决方案1】:

试试这个(注意 ProductId)

                    Brand br = new Brand();
                   {
                      br.ProductId = prod.ProductId;
                      br.BrandName = TxtBrandName.Text;
                      br.BrandDescription = TxtBrandDescription.Text;
                      br.DietType = TxtDietType.Text;
                    };

【讨论】:

    【解决方案2】:

    当您将记录插入具有外键约束的表中时,记录的外键值必须连接到它所引用的主键。

    因此,在插入品牌记录时,您需要包含以下行:

    br.ProductID = prod.ProductId;
    

    这将允许维护外键约束。

    编辑:mike123 击败了我,但你明白了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-27
      • 2021-10-31
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多