因此,我通过将模型中的对象解析为我项目中的数据库来创建了一个自定义控制器,在该控制器中,有一个名为Edit的post方法,其中包括Id、标题、描述、FileName、FileType、FileSize、Author、DateUploaded等数据库字段。
在编辑html视图中,我删除了一些元素,因为我只想编辑"Title“和"Description”,而且我还删除了我创建的控制器中的edit方法中的字段。
解释这一点;
public ActionResult Edit([Bind(Include = FileSharing "Id,Title,Description,FileName,FileType,FileSize,Author,DateUploaded")] FileSharing fileSharing)转入:
public ActionResult Edit([Bind(Include = "Id,Title,Description")] FileSharing fileSharing)当我试图编辑一个标题或描述时。它会给出一个异常错误:
System.Data.Entity.Infrastructure.DbUpdateException‘发生在EntityFramework.dll中,但未在用户代码中处理。
为什么我要得到这个错误,我如何才能避免它呢?
Edit法
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);
}发布于 2015-09-23 15:56:03
下面是我处理这个例外的方法。
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);
}然后,至少异常有更多的相关信息,这可能使您很容易发现什么是错误的(比如一些DB验证问题)。
https://stackoverflow.com/questions/32742749
复制相似问题