asp.net MVC 中的用户代码未处理 DbUpdateException
DbUpdateException was Unhandled by user code in asp.net MVC
我正在使用像 Jobbr.net 这样的聊天服务器。当我关闭群聊选项卡时,我得到 DbUpdateException
was Unhandled by user code
代码:
public void CommitChanges()
{
_db.SaveChanges();
}
您的数据模型或要保留的数据似乎有问题。我想当您尝试保存实体时,某些必填字段或外键未设置。
尝试捕获并记录 System.Data.Entity.Infrastructure.DbUpdateException
。它应该告诉您是哪个实体导致了问题。这是我们使用的一些日志记录代码:
using NLog;
private static Logger Logger = LogManager.GetCurrentClassLogger();
try {
_db.SaveChanges();
}
catch (System.Data.Entity.Infrastructure.DbUpdateException upEx) {
if (upEx.Entries != null && upEx.Entries.Any()) {
Logger.Debug("DbUpdateException contained '{0}' entries:", upEx.Entries.Count());
// get info about the Entity that produced the error
foreach (var dbEntityEntry in upEx.Entries) {
if (dbEntityEntry.Entity != null) {
var entityType = dbEntityEntry.Entity.GetType();
try {
var id = entityType.GetProperty("Id").GetValue(dbEntityEntry.Entity, null);
Logger.Debug("DbUpdateException contains DbEntityEntry - Type: '{0}', Id: '{1}', State: '{2}'", entityType.Name, id, dbEntityEntry.State.ToString("G"));
} catch (Exception) {
Logger.Debug("DbUpdateException contains DbEntityEntry - Type '{0}', Id: unknown, State: '{2}'", entityType.Name, dbEntityEntry.State.ToString("G"));
}
}
}
}
}
我正在使用像 Jobbr.net 这样的聊天服务器。当我关闭群聊选项卡时,我得到 DbUpdateException
was Unhandled by user code
代码:
public void CommitChanges()
{
_db.SaveChanges();
}
您的数据模型或要保留的数据似乎有问题。我想当您尝试保存实体时,某些必填字段或外键未设置。
尝试捕获并记录 System.Data.Entity.Infrastructure.DbUpdateException
。它应该告诉您是哪个实体导致了问题。这是我们使用的一些日志记录代码:
using NLog;
private static Logger Logger = LogManager.GetCurrentClassLogger();
try {
_db.SaveChanges();
}
catch (System.Data.Entity.Infrastructure.DbUpdateException upEx) {
if (upEx.Entries != null && upEx.Entries.Any()) {
Logger.Debug("DbUpdateException contained '{0}' entries:", upEx.Entries.Count());
// get info about the Entity that produced the error
foreach (var dbEntityEntry in upEx.Entries) {
if (dbEntityEntry.Entity != null) {
var entityType = dbEntityEntry.Entity.GetType();
try {
var id = entityType.GetProperty("Id").GetValue(dbEntityEntry.Entity, null);
Logger.Debug("DbUpdateException contains DbEntityEntry - Type: '{0}', Id: '{1}', State: '{2}'", entityType.Name, id, dbEntityEntry.State.ToString("G"));
} catch (Exception) {
Logger.Debug("DbUpdateException contains DbEntityEntry - Type '{0}', Id: unknown, State: '{2}'", entityType.Name, dbEntityEntry.State.ToString("G"));
}
}
}
}
}