2

我需要插入 Windows 窗体中的数据必须插入到两个表中。我正在为 Windows 窗体中的所有控件使用数据源。你能告诉我如何将数据从windows窗体同时插入两个表吗?

我的桌子是这样的

**product table**

pid   salePrice  


**Product_tax table**

pid  taxid

当我单击提交按钮时,产品 ID 将自动生成,并且 salePrice 必须同时从表单中存储我选择的税款,该税款也必须与产品 ID 一起存储在 product_tax 表中。请从这一点帮助我。

提前致谢。

4

2 回答 2

6

所以为了让你这样做,这是一个简单的例子,你可以理解(有更好和更复杂的方法来做到这一点)。

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();
    }
}

这应该通过调整您的解决方案来解决问题。

于 2013-08-09T08:17:56.147 回答
0

非常简单。鉴于您在表之间定义了关系,您可以执行以下操作:

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
});
于 2013-08-09T08:12:00.387 回答