如何使用实体框架一次将数据插入两个表中
本文关键字:插入 两个 数据 一次 实体 何使用 框架 | 更新日期: 2023-09-27 18:26:54
我需要插入windows表单中的数据,必须插入到两个表中。我正在为windows窗体中的所有控件使用数据源。你能告诉我如何将windows窗体中的数据同时插入到两个表中吗。
我的桌子像这个
**product table**
pid salePrice
**Product_tax table**
pid taxid
当我点击提交按钮时,产品id将自动生成,salePrice必须同时从表格中存储我选择的税款,该税款也必须与产品id一起存储在product_tax表中。请从这一点上帮助我。
提前感谢
因此,为了做到这一点,这是一个简单的示例,以便您能够理解(有更好、更复杂的方法来实现这一点)。
private void AddProducts(double salePrice, int taxValue)
{
using (var ctx = new Entity())
{
Product prodObject = new Product
{
PId = //NEW ID,
SalePrice = salePrice
};
Product_tax pTax = new Product_tax
{
pid = prodObject.PId,
taxid = taxValue
};
ctx.product.AddObject(prodObject);
ctx.Product_tax .AddObject(pTax);
ctx.SaveChanges();
}
}
这应该通过调整你的解决方案来达到目的。
非常简单。如果您在表之间定义了关系,您可以执行以下操作:
using ( Entity EF = new Entity()){
EF.addToProductTax(new ProductTax(){
Product = new Product(){
pid = //your generated Product id,
salePrice = price
},
Tax = (FROM t in EF.tax where t.taxid == taxid select t);
});
}
为了更容易理解:
Product item = new Product();
item.salePrice = price;
// pid gets generated automatically !
Tax correspondingTax = (from t in EF.tax where t.taxid == taxid select t);
Product_Tax add = new Product_Tax;
add.Product = item;
add.Tax = correspondingTax;
EF.addToProductTax(add);
请记住,只有在两个表之间定义了关系时,这才有效。在其他任何情况下,你都必须这样做:
EF.addToTax(new Tax(){
taxid = taxid,
// and all the other fields
});
EF.addToProducts(new Product(){
pid = pid,
salePrice = saleprice
});
EF.addToProductTax(new ProductTax(){
pid = pid,
taxid = taxid
});