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

允我心安 提交于 2019-12-22 00:11:32

问题


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:


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.




回答2:


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


来源:https://stackoverflow.com/questions/18142456/how-to-insert-data-into-two-tables-at-a-time-using-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!