When I am tiring to insert the data into MySQL using excel sheet using entity framework, Here I want to handle exception inside the loop for each record so , I used try --catch within the loop
enter code here
foreach (DataRow dr in ds.Tables[0].Rows)
{
outstanding_master master = new outstanding_master();
{
//log.Debug("This a test debug message");
master.LoanID = dr["LoanID"].ToString();
master.Name = dr["Name"].ToString();
master.PhoneNumber = Convert.ToInt64(dr["PhoneNumber"].ToString());
master.Address = dr["Address"].ToString();
master.ServiceProviderID = Convert.ToInt32(dr
["ServiceProviderID"].ToString());
master.TotalDue = dr["TotalDue"].ToString();
master.LastPaidAmount = dr["LastPaidAmount"].ToString();
master.LastPaidDate = Convert.ToDateTime(dr["LastPaidDate"].ToString());
master.OutStandingDescription = dr["OutStandingDescription"].ToString();
master.longitude = dr["longitude"].ToString();
master.latitude = dr["latitude"].ToString();
db.outstanding_master.Add(master);
try
{
db.SaveChanges();
log.Info("Record saved successfully with LoanID: " + master.LoanID);
}
catch (Exception ex)
{
log.Info("Error saving record with LoanID: " + dr["LoanID"].ToString() + " Exception(): " + ex.InnerException.InnerException);
var entry = db.Entry(master);
if (entry.State == EntityState.Added)
{
((System.Data.Entity.Infrastructure.IObjectContextAdapter)db).ObjectContext.DeleteObject(master);
}
} } }
Here when the object of Outstanding is attachment if no exception it's should inserted into database if not show exception and loop again for next transaction and detach the previous record object.
Here my problem is when I insert the 3 records without any exception working fine, if two record are failed and last 3rd records is no exception it's should inserted working fine but if 1st record inserted ,2nd records failed with some exception(duplicate key) than 3rd record also fail with below exception but it's should insert((exception:Nested transactions are not supported)
Please try below link It is probably caused by 2 different connections used in transaction. You should control connection manually: solution form below link may be it's helps to you
In Entity Framework 4.0 "Nested transactions are not supported" error is displayed?