Entity framework -Save datatable to SQL server without for each loop

c# entity-framework-6

Question

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?

1
3
3/20/2017 2:15:52 PM

Accepted Answer

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();
6
3/20/2017 12:11:48 PM

Popular Answer

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.



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