I have this method below that is writing data to two tables in the database. There is a collection I need to write to the database in the foreach section. Is it okay if I call saveChanges in each iteration of the loop or is there a better way of doing this?
public string SaveInformationToDb(Customerproductdto objDataCollected, List<Productopportunity> objcheckedData)
{
int generatedLeadDescriptionId = 0;
string result = "Failure";
using (var dbcontext = new LEADSEntities())
{
using (var dbContextTransaction = dbcontext.Database.BeginTransaction())
{
var leadDescription = new LEAD_DESCRIPTION
{
DETAIL = objDataCollected.LeadDetails,
EstimatedRevenue = Convert.ToDecimal(objDataCollected.EstimatedRevenue),
CustomerContact = objDataCollected.CustomerContact,
CustomerPhone = objDataCollected.CustomerPhone,
CustomerEmail = objDataCollected.CustomerEmail
};
dbcontext.LEAD_DESCRIPTION.Add(leadDescription);
dbcontext.SaveChanges();
generatedLeadDescriptionId = leadDescription.ID;
//process data in the collection
foreach (var VARIABLE in objcheckedData)
{
var leadMetric = new LEAD_METRIC
{
EMPLID = objDataCollected.EmployeeNumber,
CustomerNumber = objDataCollected.CustomerNumber,
ProductTypeId = GetLeadProductOpportunityId(VARIABLE.ProductName),
LeadId = generatedLeadDescriptionId
};
dbcontext.LEAD_METRIC.Add(leadMetric);
dbcontext.SaveChanges();
}
result = "Success";
dbContextTransaction.Commit();
}
}
return result;
}