In following code, multiple queries will be run against the database for inserting one row at a time.
EF cause Multiple Database Trips: When I call c.SaveChanges, then EF 4.0 will run multiple UPDATE statements against the database, but will execute only one UPDATE per database trip. This means if we have 1000 UPDATE statements generated by EF 4.0, then we will end up making 1000 database trips, which is NOT a GOOD and OPTIMAL data approach in my view.
Is there any way of making EF 4.0 run a single batched query for all records updates in a single database trip? May be, if I could get the UPDATE query ( I mean the SQL query) for each record update, then I could just put all these queries into a single batched query and send the batched query to database, but I don't know if the UPDATE query for each record can be obtained in EF 4.0.
public void SaveVendorOrders(int vendorId, int parentVendorId, string tag,
string desc, int productSegment, int productCategory)
{
using (Vendor c = new Vendor())
{
var query = (from p in c.Orders
where (p.VendorID == vendorId ||
p.ParentVendorID == parentVendorId)
select p);
if (query.ToList().Count() > 0)
{
for (int i = 0; i <= query.ToList().Count() - 1; i++)
{
query.ToList()[i].OrderTag = tag;
query.ToList()[i].OrderDescription = desc;
query.ToList()[i].ProductSegment = productSegment;
query.ToList()[i].ProductSegmentCategory = productCategory;
}
c.SaveChanges();
}
}
}
EDIT 1:
As pointed out by SJuan76 and Hamlet Hakobyan, calling ToList repeatedly will execute a query repeatedly. But even that is solved by cleaning the code so ToList is called only once, my question remains: How to combine multiple updates into a single batched update query?