【发布时间】: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