问题
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