I m building a code to save more data into SQL database, using Entity Framework 5.0
I m build this code:
foreach (EcgDTO.HrvData data in u.hrvData)
{
if (data.hrv != null && data.hrv.Count > 0)
{
foreach (String d in data.hrv)
{
ECG ecg = new ECG();
ecg.Id = id++;
ecg.IdPerson = idPatient;
ecg.y = Decimal.Parse(d);
ecg.timestamp = data.createdDate;
dbData.ECG.Add(ecg);
}
}
}
int savedData = dbData.SaveChanges();
This is ECG Class
[DataContract]
public class EcgDTO
{
[DataMember(Name = "hrvData")]
public List<HrvData> hrvData { get; set; }
public class HrvData
{
[DataMember(Name = "patientId")]
public String patientId { get; set; }
[DataMember(Name = "hrv")]
public List<String> hrv { get; set; }
[DataMember(Name = "createdDate")]
public DateTime createdDate { get; set; }
[DataMember(Name = "createdBy")]
public String createdBy { get; set; }
[DataMember(Name = "modifiedBy")]
public String modifiedBy { get; set; }
[DataMember(Name = "modifiedDate")]
public DateTime modifiedDate { get; set; }
}
}
Now my input List can have 227 items, and HRV list have 67 values
Is there a way to improve the speed of scrolling of the two lists and saving on the database?
dbData.ECG.Add(ecg);in the loop. This is fine for a small number of records but callingdbData.ECG.AddRangeis much more performant. You can create a new list of entities,List<T>, add to this list in the loop, and then callAddRangeand pass this list. I am not saying that will fix whatever problem you have, you first have to do some profiling to figure out why your code execution is slow.SaveChangesslow though? Are there any other queries locking that table? Do you keep connections or transactions open for long? Did you actually check what's going on in the database? In SQL Server, open SSMS and click on Activity Monitor. Is the server busy? Any expensive queries? Any blocked connections?