简体   繁体   中英

how to insert data into two tables at a time using entity framework

i need to insert data which is in windows forms has to insert to two tables. i am using data source for all controls in windows forms. can you please sugest me how to insert data from windows forms into two tables at same time.

my table is like this

**product table**

pid   salePrice  


**Product_tax table**

pid  taxid

When i click on submit button product id will auto generate and salePrice has to store from form at same time what ever i select tax that also has to store in product_tax table along with product id. please help me out from this point.

Thanks in advance.

So in order for you to do so, this is a simple example so that you can understand ( there are better and more sophisticated ways to do this ).

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

This should do the trick with a tweak to your solution.

quite simple. Given the case you have a relationship defined between the tables you can do the following:

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

for easier comprehension:

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

Remember, this only works if you have a relationship defined between the two tables. in every other case you will have to do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM