如何使用实体框架一次将数据插入到两个表中

时间:2013-08-09 08:03:56

标签: c# sql entity-framework windows-applications

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

我的桌子就像这样

**product table**

pid   salePrice  


**Product_tax table**

pid  taxid

当我点击提交按钮时,产品ID将自动生成并且salePrice必须同时存储表格,我必须选择税收,同时还必须存储在product_tax表中以及产品ID。请从这一点帮助我。

提前致谢。

2 个答案:

答案 0 :(得分: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();
    }
}

这应该可以通过调整解决方案来实现。

答案 1 :(得分: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
});