2017-10-04 77 views
2

我有两个表即。 tblProduct and Brands,tblProduct包含: ProductId,ProductName,Quantity,Price,Entry_Date。 和品牌包含:ProductId,BrandID,BrandName,BrandDescription,DietType,ProductId(来自tbProduct的FK)。无法将值NULL插入到'ProductId'列'ProductDB.dbo.Brand'列中;

我使用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),但没有插入品牌表中的任何东西,我不确定这里的问题似乎是什么问题。 请注意BrandID和ProductId(在两个表上)都设置为自动增量。

+1

品牌表中的外键对产品表有限制吗?如果是这样,您需要将已插入产品表的产品ID包含在品牌表 – RH6

+0

@ RH6中,这要感谢您提前回应,是的,ProductId是品牌表中的外键,我也已设置自动递增。你是说我应该包括像prod.ProductId = br.ProductId? –

+1

您需要从先前插入的产品表中检索主键(productID),然后在插入到品牌表中时,外键必须与此匹配(假设它们为1到1)。 编辑:本质我刚刚发布的答案是 – RH6

回答

1

试试这个(注意产品ID)

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

好的,我会尝试这种方法谢谢你。 –

1

当你插入一条记录到一个表的外键约束,记录的外键值必须连接到它引用的主键。

所以将品牌记录时,您将需要加入这一行:

br.ProductID = prod.ProductId; 

这将允许保持外键约束。

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

相关问题