DbUpdateException was unhandled? - c#

Hi so keep encountering this exception every time when savechanges() is called. There is an other post that has multiple answers but, I cannot pin point which answer is suitable for my problem. Also it seems that everyone has a different opinion about this exception.
Link to other post: [a link] Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."
My Exception:
An unhandled exception of type
'System.Data.Entity.Infrastructure.DbUpdateException' occurred in
EntityFramework.dll
Additional information: An error occurred while updating the entries.
See the inner exception for details.
I am trying to save mails into my storage. I am using entity framework 6.1.3 and SQL server 2014.
This is my method that stores mails:
public int StoreMail(PhishingMail PhishingMail)
{
using (var phishingMailStorage = new PhishFinderDBModel())
{
try
{
//// var manager = ((IObjectContextAdapter)phishingMailStorage).ObjectContext.ObjectStateManager;
//// phishingMailStorage.PhishingMail.Attach(PhishingMail);
phishingMailStorage.Entry(PhishingMail).State = PhishingMail.PhishingMailId == 0 ? EntityState.Added : EntityState.Modified;
phishingMailStorage.SaveChanges();
//// manager.ChangeObjectState(PhishingMail, EntityState.Modified);
//// phishingMailStorage.SaveChanges();
Console.WriteLine("Het is gelukt");
}
catch (OptimisticConcurrencyException)
{
var ctx = ((IObjectContextAdapter)phishingMailStorage).ObjectContext;
ctx.Refresh(RefreshMode.ClientWins, phishingMailStorage.PhishingMail);
phishingMailStorage.SaveChanges();
}
}
return PhishingMail.PhishingMailId;
}
This is my get mails method, that does work:
public List<PhishingMail> GetEmails()
{
phishingMailList = new List<PhishingMail>();
FolderId InboxId = new FolderId(WellKnownFolderName.Inbox, "******#******.nl");
FindItemsResults<Item> findResults = service.FindItems(InboxId, new ItemView(20));
foreach (Item phishingmail in findResults.Items)
{
if (!((EmailMessage)phishingmail).IsRead)
{
/// ((EmailMessage)phishingmail).IsRead = true;
((EmailMessage)phishingmail).Update(ConflictResolutionMode.AutoResolve);
}
PhishingMail mail = MailMapper.Map((EmailMessage)phishingmail);
//// ((EmailMessage)phishingmail).Load(new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.IsRead));
phishingMailList.Add(mail);
/// Console.WriteLine(mail.Type);
}
return phishingMailList;
}
Why does savechanges() not work and how do I make it work?
Thank you.

write your db.SaveChanges(); method inside a try block. It will tell you the exact problem
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
Exception raise = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}

Related

Try Catch - The transaction associated with the current connection has completed but has not been disposed

I am getting Error : The transaction associated with the current connection has completed but has not been disposed. after Log.WriteEntry($"Error occurred while trying to create invoice for transaction {transaction.TransactionLogId} : {ex.Message}"); statement when i run the code.. Can someone please help?
public virtual GroupCreationResult CreateGroups(IEnumerable<TransactionDetail> transactions)
{
var transactionDetails = transactions as TransactionDetail[] ?? transactions.ToArray();
var successes = new List<int>(transactionDetails.Length);
var errors = new List<TransactionError>();
foreach (var transaction in transactionDetails)
{
using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted, Timeout = new TimeSpan(0, 2, 0) }))
{
try
{
foreach (var service in _invoiceCreationServices)
{
try
{
service.CreateInvoice(transaction);
}
catch (Exception ex)
{
Log.WriteEntry($"Error occurred while trying to create invoice for transaction {transaction.TransactionLogId} : {ex.Message}");
if (!(ex.ToString().Contains("Violation of PRIMARY KEY constraint 'PK_APInvGrp'.") || ex.ToString().Contains("Violation of PRIMARY KEY constraint .")))
{
Log.WriteEntry($"error occured while adding the transaction {transaction.TransactionLogId} - {ex.ToString()}");
errors.Add(new TransactionError(transaction.TransactionLogId, ex.ToString()));
scope.Complete();
break;
}
}
}
Log.WriteEntry($"successfully added the transaction {transaction.TransactionLogId}");
successes.Add(transaction.TransactionLogId);
scope.Complete();
}
catch (Exception exception)
{
Log.WriteEntry($"error1 occured while adding the transaction {transaction.TransactionLogId} - {exception.ToString()}");
//errors.Add(new TransactionError(transaction.TransactionLogId, exception.ToString()));
}
}
}
return BuildGroupCreationResult(successes, errors);
}

Can't save record using Entity Framework

My objects will not save no matter what I do they will fetch and get info and make a new record but not update.
This is the code that details with getting existing patient and then modifying the record setting the state then calling save change this is cracking my head the last three hours what is going wrong. I was told you had to change the entity state of an object before it would no if to save but when i try to attach it it says its already attached
Appointment _appointment = new Appointment();
int errorCount = 0;
Patient _patient = SourceDal.getPatientByPatientNewId(Convert.ToInt32(txtPatientId.Text));
_patient.SSN = txtSSN.Text;
_patient.FirstName = txtPatientFirstName.Text;
_patient.LastName = txtPatientLastName.Text;
_patient.Middle = txtPatientMiddle.Text;
_patient.AddressOne = txtPatientAddressOne.Text;
_patient.City = txtPatientCity.Text;
_patient.State = txtPatientState.Text;
_patient.ZipCode = txtPatientZip.Text;
_patient.HomePhone = txtPatientHomePhone.Text;
_patient.WorkPhone = txtPatientWorkPhone.Text;
_patient.CellPhone = txtPatientCellPhone.Text;
if (rBtnHomePhone.Checked == true)
// _patient.ApptPhone = txtPatientHomePhone.Text;
if (rBtnHomePhone.Checked == true)
// _patient.ApptPhone = txtPatientHomePhone.Text;
if (rBtnWorkPhone.Checked == true)
// _patient.ApptPhone = txtPatientWorkPhone.Text;
_patient.BirthDate = dtBirthDate.DateTime;
_patient.emailAddress = txtPatientEmail.Text;
_patient.Race = Convert.ToInt32(dpRace.SelectedValue);
_patient.Ethnicity =Convert.ToInt32(dpEthnicity.SelectedValue);
_patient.Language = Convert.ToInt32(dpLanguages.SelectedValue);
if (dpGender.Text == "")
{
dpGender.Focus();
errorCount = 1;
lblGenderRequired.Text = "* Gender is required.";
}
else
{
errorCount = 0;
lblGenderRequired.Visible = false;
}
_patient.Gender = "M";
_patient.PatientID = txtPatientId.Text;
SourceDal.SourceEntities.Patients.Attach(_patient);
SourceDal.SourceEntities.Patients.Context.ObjectStateManager.ChangeObjectState(_patient, EntityState.Modified);
SourceDal.SourceEntities.SaveChanges();
The error I get is
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.Entity.dll
Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
Edit 2:
Code to show my function getPaitnetByPatineyNewId
public Patient getPatientByPatientNewId(int newId)
{
Patient patient = new Patient();
if (newId == -1)
{
patient = new Patient();
}
else
{
patient = SourceEntities.Patients
.Where(w => w.ID == newId)
.FirstOrDefault();
}
return patient;
}
I think you have some issues with proper separation of concerns within your DAL, but for the short solution, you should only add (and not attach) if it's a new entity
if (_patent.PatentId == 0)
{
_patient.PatientID = txtPatientId.Text; // If you're using an identity column, remove this line. I would also strongly suggest not letting the user change this...
SourceDal.SourceEntities.Patients.Add(_patient);
}
For Anyone else the above scenarios did not work for me so this is what I had to do. I put a flag on my forms isUpdate and check that on the save button then if save call similar to below then if add just call savechanges and its now working thank you for everyone help hope this help someone.
public void SaveProviders(Provider _providers)
{
try
{
using (var ctx = new SMBASchedulerEntities(this.Connectionstring))
{
ctx.Providers.Add(_providers);
ctx.Entry(_providers).State = System.Data.Entity.EntityState.Modified;
ctx.SaveChanges();
}
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}

( {"An error occurred while updating the entries. See the inner exception for details."} )

Everytime I run the program the error occures on db.SaveChanges()! Please, could anyone help with the solution?
[HttpPost]
public ActionResult Create(HttpPostedFileBase picture, form _form)
{
try
{
string ImageName = Path.GetFileName(picture.FileName);
string physicalPath = Server.MapPath("~/images/" + ImageName);
picture.SaveAs(physicalPath);
form new1 = new form();
new1.Name = _form.Name;
new1.Email = _form.Email;
new1.Phone = _form.Phone;
//.......saving picture url......
new1.DataImage = physicalPath;
//Assign for remaining feilds in table in this way.
db.forms.Add(new1);
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
Exception raise = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
// raise a new exception nesting
// the current instance as InnerException
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return View();
}
}
There might be null value in your Form object.

'System.Data.Entity.Infrastructure.DbUpdateException' I dont know why my program is throwing me this error

I am an amateur to web programming.
Currently working with c#, MVC, js/ts, and jquery.
When I try and SaveChanges to my database I get this error:
" 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in
EntityFramework.dll. Additional information: An error occurred while
updating the entries. See the inner exception for details. "
There are no inner details. This is what I am trying to do.
Order order = new Order();
TryUpdateModel(order);
try
{
if (string.Equals(values["PromoCode"], PromoCode,
StringComparison.OrdinalIgnoreCase) == false)
{
return View(order);
}
else
{
order.Username = User.Identity.Name;
order.OrderDate = DateTime.Now;
//Save Order
storeDB.Orders.Add(order);
storeDB.SaveChanges();
//Process the order
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.CreateOrder(order);
return RedirectToAction("Complete",
new { id = order.OrderId });
}
}
catch (System.Data.Entity.Core.UpdateException e)
{
return View(order);
}
catch (System.Data.Entity.Infrastructure.DbUpdateException ex) //DbContext
{
Console.WriteLine(ex.InnerException);
return View(order);
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
//Invalid - redisplay with errors
return View(order);
}
it fails at cart.CreateOrder(order);
this is what CreateOrder(order) does
decimal orderTotal = 0;
var cartItems = GetCartItems();
// Iterate over the items in the cart,
// adding the order details for each
foreach (var item in cartItems)
{
var orderDetail = new OrderDetail
{
GameId = item.GameId,
OrderId = order.OrderId,
UnitPrice = item.Game.Price,
Quantity = item.Count
};
// Set the order total of the shopping cart
orderTotal += (item.Count * item.Game.Price);
storeDB.OrderDetails.Add(orderDetail);
}
// Set the order's total to the orderTotal count
order.Total = orderTotal;
// Save the order
storeDB.SaveChanges();
// Empty the shopping cart
EmptyCart();
// Return the OrderId as the confirmation number
return order.OrderId;
it gives me the error message at storeDB.SaveChanges();
everything is spelt the way it is suppose to.
Anything you guys think I am missing?
The DbUpdateException is caused by mostly database constraint violations. You should be showing the additional code to deal with the DbUpdateException:
try
{
....
}
catch (DbUpdateException ex)
{
UpdateException updateException = (UpdateException)ex.InnerException;
SqlException sqlException = (SqlException)updateException.InnerException;
foreach (SqlError error in sqlException.Errors)
{
// TODO: Do something with your errors
}
}
We figured it out. When saving our changes to the database we forgot to fill in a column for that entry. Very stupid =P. I was working with a partner and thought they took care of all that stuff.
Thanks guys

An error occurred while preparing the command definition. See the inner exception for details EF

An error occurred while updating the entries. See the inner exception for details.
Inner exception : "An error occurred while preparing the command definition. See the inner exception for details."
I'm using Oracle as Entity Framework and Database.
When i am trying get result using EF it's working fine. But when i am trying to insert a record into the table I am getting this issue.
This is the code:
try{
Table1 Obj = new Table1();
Obj.col1 = 2010;
Obj.col2 =0;
Obj.col3 = 103907;
Obj.col4 = 14145;
DataContext1 dbContext = new DataContext1();
dbContext.AddToTable1(Obj);
dbContext.ObjectStateManager.ChangeObjectState(Obj,System.Data.EntityState.Added);
dbContext.SaveChanges();
}catch(Expectation ex)
{
}
You need to look at the inner exception. The issue will probably be obvious from there.
Something like this might help (or set a breakpoint and just look):
try{
Table1 Obj = new Table1();
Obj.col1 = 2010;
Obj.col2 =0;
Obj.col3 = 103907;
Obj.col4 = 14145;
DataContext1 dbContext = new DataContext1()
dbContext.AddToTable1(Obj);
dbContext.ObjectStateManager.ChangeObjectState(Obj,System.Data.EntityState.Added);
dbContext.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
string validationErrors = "DbEntityValidationException ValidationErrors: ";
foreach (var k in e.EntityValidationErrors)
{
foreach (var e1 in k.ValidationErrors)
{
validationErrors += string.Format("{0} - {1}; ", e1.PropertyName, e1.ErrorMessage);
}
}
throw new Exception(validationErrors, e);
}

Categories