我有两个表即。 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(在两个表上)都设置为自动增量。
品牌表中的外键对产品表有限制吗?如果是这样,您需要将已插入产品表的产品ID包含在品牌表 – RH6
@ RH6中,这要感谢您提前回应,是的,ProductId是品牌表中的外键,我也已设置自动递增。你是说我应该包括像prod.ProductId = br.ProductId? –
您需要从先前插入的产品表中检索主键(productID),然后在插入到品牌表中时,外键必须与此匹配(假设它们为1到1)。 编辑:本质我刚刚发布的答案是 – RH6