how to insert data into two tables at a time using entity framework
16,198
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.
Author by
Sheela K R
Updated on June 29, 2022Comments
-
Sheela K R almost 2 years
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.
-
Sheela K R over 10 yearsProdouctTax table.. Productid is FK of Product table and TaxID is FK of Tax table. in store Procedure We can use @@Identity. But i am not getting how to use it in entity model
-
Vogel612 over 10 yearsyou should be able to just do:
ProductTax.Tax.property;
. so if I understand correctly, Product_Tax is just a relationship table. this means you can go even further:Product.ProductTax.Tax.property;
. but to do this you will need to load the Entity Context. -
Vogel612 over 10 yearsare you sure you can't just do
Product = prodObject,
in pTax? -
Madax over 10 years@Vogel612 Just to simplify the understanding of the code due to the question that was regarding the ID. That way, you can see on the code where it comes from and how it connects. :)
-
Vogel612 over 10 yearshmm. keep in mind that
pTax
also has a Tax. this is only a relational table (not that one would actually need it) -
Madax over 10 years@Vogel612, yep... let's just assume there is more to it then the example... ;) but you are correct!!
-
ErTR about 8 yearsWhat are the better and more sophisticated ways? How to dig more?