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

c# entity-framework sql windows-applications

Question

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.

1
2
8/9/2013 8:03:56 AM

Accepted Answer

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.

6
8/9/2013 8:17:56 AM

Popular Answer

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow