I'm developing application with c#.net entity framework and sql server 2008r2. Here is my code
C#.net Code
foreach (var tempProduct in purchaseDetailTemp)
{
invPurchase = new InvPurchaseDetailTemp();
invPurchase.ProductID = tempProduct.InvProductMasterID;
invPurchase.ProductCode = tempProduct.ProductCode;
invPurchase.ProductName = tempProduct.ProductName;
context.InvPurchaseDetails.Add(invPurchase);
context.SaveChanges();
}
purchaseDetailTemp is my datatable. I want to save data without foreach
loop. I'm trying this with mergeSql and bulk insert. Is there a way to do that?
move the saveChange out of the loop.
to make it faster... you can use the AddRange option on the context entity, which reduces the entity model checks.
The for-loop is just to convert it to the correct entity type. if it was already the right type then the loop could be skipped
see below..
List<InvPurchaseDetail> invPurchaselist = new List<InvPurchaseDetail>();
foreach (var item in purchaseDetailTemp)
{
var newItem= new InvPurchaseDetail();
newItem.ProductID = item.InvProductMasterID;
newItem.ProductCode = item.ProductCode;
newItem.ProductName = item.ProductName;
invPurchaselist.add(newItem)
}
context.InvPurchaseDetails.AddRange(invPurchaselist);
context.SaveChanges();
EntityFramework has changetracking, which means that when you do execute .SaveChanges();
it persists all updates to the data source and resets change tracking in the object context.
This also means, if you want to bulk insert you still need to iterate but you can move .SaveChanges();
out of your iteration scope to only execute towards the database once.