System.Data.Entity.Infrastructure.DbUpdateException occurred - c#

So I have made a custom controller by parsing objects in a model to a database in my project and inside that controller, there is a post method called Edit which includes the database fields such as Id, Title, Description, FileName, FileType, FileSize, Author,DateUploaded
In the edit html view, I removed some elements because all I want to edit is "Title" and "Description" and I have also removed the fields in the edit method in the controller I created.
To explain that;
public ActionResult Edit([Bind(Include = FileSharing "Id,Title,Description,FileName,FileType,FileSize,Author,DateUploaded")] FileSharing fileSharing)
into:
public ActionResult Edit([Bind(Include = "Id,Title,Description")] FileSharing fileSharing)
When I try to edit a title or description. It will give a exception error saying
System.Data.Entity.Infrastructure.DbUpdateException' occurred in
EntityFramework.dll but was not handled in user code
Why am I getting this error and how can I get around it?
Edit method
public ActionResult Edit([Bind(Include = "Id,Title,Description")] FileSharing fileSharing)
{
if (ModelState.IsValid)
{
try
{
db.Entry(fileSharing).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception)
{
ViewBag.EditFail = "Error editing file details.";
}
}
return View(fileSharing);
}

Here's how I handle that exception.
private Exception HandleDbUpdateException(DbUpdateException dbu)
{
var builder = new StringBuilder("A DbUpdateException was caught while saving changes. ");
if (!(dbu.InnerException is System.Data.Entity.Core.UpdateException) ||
!(dbu.InnerException.InnerException is System.Data.SqlClient.SqlException))
{
try
{
foreach (var result in dbu.Entries)
{
builder.AppendFormat("Type: {0} was part of the problem. ", result.Entity.GetType().Name);
}
}
catch (Exception e)
{
builder.Append("Error parsing DbUpdateException: " + e);
}
}
else
{
var sqlException = (System.Data.SqlClient.SqlException)dbu.InnerException.InnerException;
for (int i = 0; i < sqlException.Errors.Count; i++)
{
builder.AppendLine(" SQL Message: " + sqlException.Errors[i].Message);
builder.AppendLine(" SQL procedure: " + sqlException.Errors[i].Procedure);
}
}
string message = builder.ToString();
return new Exception(message, dbu);
}
Then at least the exception has more relevant information, which probably makes it easy for you to figure out what's wrong (like some DB validation issue).

Related

System.Data.Entity.Validation.DbEntityValidationException 2022

Iam trying to edit information from a table in my database. I can insert the information into the table, but when I try to edit that info, I got the following error message. Any help? please
System.Data.Entity.Validation.DbEntityValidationException: 'Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.'
This is my controller Edit: I got the error in the " context.SaveChanges(); " line
[HttpGet]
public ActionResult Editar(int id)
{
Cafeteria_POSEntities context = new Cafeteria_POSEntities();
Faculty empleado = context.Faculties.Single(x => x.Employee_ID == id);
ViewBag.Meal_Plan = GetPlanesSelect();
return View(empleado);
}
[HttpPost]
[ActionName("Editar")]
public ActionResult Editar(Faculty empleado)
{
if (ModelState.IsValid)
{
Cafeteria_POSEntities context = new Cafeteria_POSEntities();
context.Entry(empleado).State = EntityState.Modified;
context.SaveChanges();
return RedirectToAction("Index");
}
return View(empleado);
}
The 'DbEntityValidationException' is an exception that suggests problems with the data you are trying to insert/update in your context/database. I cannot see here because there is not provided input data or the table in your database, but I would say that you either, have a wrong data type for some property, some property might be null which is not allowed, or maybe breaking some primary/foreign key rules.

Error with telegrambot in webapi

I have written a telegram bot with webapi in asp.net and it receives updates but in the response the bot sends me this error:
error:System.NullReferenceException: Object reference not set to an instance of an object.
at WebApiNew.Controllers.WebhookController.Post(Update update)
and my code:
[HttpPost]
public string Post(Update update)
{
if (update != null)
{
try
{
var chatid = update.Message.Chat.Id;
var text = update.Message.Text;
bot.SendTextMessage(chatId: chatid, text: text);
}
catch (Exception ex)
{
bot.SendTextMessage(chatId: 158272989, text: "error :" + ex.ToString());
}
}
else {
bot.SendTextMessage(chatId: 158272989, text: "error ");
}
return "";
}
Where is the problem?
Updates come as a collection of Update objects
Maybe modify your code so post handles an array of updates

SaveChanges throws System.Data.Entity.Core.EntityException

I'm having an issue trying to update the AspNetUsers database in MVC 5 with ASP.NET.
I'm trying to change a value in the user, Credits, which is stored in the database defined as Models.UserDB2.AspNetUsers.
However, when I attempt this, I get thrown this error.
A first chance exception of type 'System.Data.Entity.Core.EntityException' occurred in EntityFramework.SqlServer.dll
FATAL ERROR: An error occurred while starting a transaction on the provider connection. See the inner exception for details.`
Inner exception:
A first chance exception of type 'System.Data.Entity.Core.EntityException' occurred in EntityFramework.SqlServer.dll is the inner exception
This is the code causing the error.
if(player != null) {
foreach(Models.Item item in itemDB.Items) {
if(item.UserAssetOptionId == id) {
if(!item.Owner.ToLower().Equals(username.ToLower())) {
return Content("false");
} else {
item.Owner = "HomeguardDev";
item.InMarket = true;
player.Credits += item.Value / 10;
try {
itemDB.SaveChanges();
userDB2.SaveChanges();
return Content("true");
} catch(Exception e) {
Debug.WriteLine("FATAL ERROR: " + e.Message);
return Content("false");
}
}
}
}
}
The database updates fine if I only update the itemDB database, but I need to update the Credits value as well!
The model is updated with the latest schema with the database, so no problems there.
Anyone know what's up?
The problem is that you're trying to save the changes to itemDB while you're still iterating itemDB.Items, try to change your code to:
if (player != null) {
foreach(Models.Item item in itemDB.Items) {
if (item.UserAssetOptionId == id) {
if (!item.Owner.ToLower().Equals(username.ToLower())) {
return Content("false");
} else {
item.Owner = "HomeguardDev";
item.InMarket = true;
player.Credits += item.Value / 10;
break;
}
}
}
try {
itemDB.SaveChanges();
userDB2.SaveChanges();
return Content("true");
} catch (Exception e) {
Debug.WriteLine("FATAL ERROR: " + e.Message);
return Content("false");
}
}
As long as you're in the foreach, you can't start a second transaction.

.ApplyCurrentValues throws exception stating entity key not matching

This is the exception I get:
"An object with a key that matches the key of the supplied object could not be found in the ObjectStateManager. Verify that the key values of the supplied object match the key values of the object to which changes must be applied."
It is trown by the next line:
public void UpdateTransaction(Transaction transaction)
{
db.Transactions.ApplyCurrentValues(transaction);
}
I read on this page that the error might becouse it is not attached, but when I try to attach it I get another exception:
"An entity object cannot be referenced by multiple instances of IEntityChangeTracker."
By doing some reading that this means that the record is already attached to the model.
And when I try to detach it I get the next:
"The object cannot be detached because it is not attached to the ObjectStateManager."
This is my controller where I update the table "InputValue", now depending on the value I also want to make an update on the table "Transaction" wich is done by the updatedTransactions function.
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var inputValue = inputValueRespository.GetInputValue(id);
if (inputValue == null)
return RedirectToAction("Index");
try
{
UpdateModel(inputValue, collection.ToValueProvider());
inputValue.InputValues_EditUser = WindowsIdentity.GetCurrent().Name;
inputValue.InputValues_EditDate = DateTime.Today.Date;
inputValueRespository.UpdateInputValue(inputValue);
List<Transaction> updatedTransactions = inputValueRespository.HasTransactions(inputValue.Input_ID, inputValue.InputValues_Date, inputValue.InputValues_Week, inputValue.InputValues_Quarter);
for (int i = 0; i < updatedTransactions.Count; i++)
{
transactionRepository.UpdateTransaction(updatedTransactions[i]);
}
inputValueRespository.save();
return RedirectToAction("Create");
}
catch (Exception)
{
return View("Create");
}
This is the function:
public List<Transaction> HasTransactions(int id, DateTime date, string week, string quarter)
{
// random code that decides if transaction should be update
Transaction transaction = new Transaction();
transaction = (from a in db.Transactions where a.KPI_ID == kpiId && a.Transaction_Period == period select a).SingleOrDefault();
// random code that generated new result
// fill the list of transaction that will be returned
transaction.Transaction_Value = result;
trasactions.Add(transaction);
}
}
return trasactions;
}
I'm completly clueless in this one, any help would be greatly appreciated.
PS: any other code where I use ApplyCurrentValue works perfectly.
I finally got it working ( by trial and error )
In the end I need the detach the object, attach it, modify, apply and then save.
db.Transactions.Detach(transaction);
db.Transactions.Attach(transaction);
transaction.Transaction_Value = result;
db.Transactions.ApplyCurrentValues(transaction);
db.SaveChanges();
Does not make a lot of sense but I guess it is just the way it works :)

How to update a database with new information

I am terrible with databases so please bear with me.
I have a program that gets some user information and adds it to a database table. I then later need to get more information for that table, and update it. To do so I have tried doing this:
public static void updateInfo(string ID, string email, bool pub)
{
try
{
//Get new data context
MyDataDataContext db = GetNewDataContext(); //Creates a new data context
//Table used to get user information
User user = db.Users.SingleOrDefault(x => x.UserId == long.Parse(ID));
//Checks to see if we have a match
if (user != null)
{
//Add values
user.Email = email;
user.Publish = publish;
}
//Prep to submit changes
db.Users.InsertOnSubmit(user);
//Submit changes
db.SubmitChanges();
}
catch (Exception ex)
{
//Log error
Log(ex.ToString());
}
}
But I get this error:
System.InvalidOperationException: Cannot add an entity that already exists.
I know this is because I already have an entry in the table, but I don't know how to edit the code to update, and not try to make a new one?
Why does this not work? Wouldn't submitting changes on a current item update that item and not make a new one?
The problem is
//Prep to submit changes
db.Users.InsertOnSubmit(user);
Because you got the user from the DB already, you don't need to re-associate it with the context.
Comment that out and you're good to go.
Just a style / usage comment as well. You should dispose your context:
public static void updateInfo(string ID, string email, bool pub)
{
try
{
using (MyDataDataContext db = GetNewDataContext())
{
User user = db.Users.SingleOrDefault(x => x.UserId == long.Parse(ID));
if (user != null)
{
user.Email = email;
user.Publish = publish;
}
db.SubmitChanges();
}
}
catch (Exception ex)
{
//Log error
Log(ex.ToString());
// TODO: Consider adding throw or telling the user of the error.
// throw;
}
}

Categories

Resources