我正在使用数据库“向导”设置中的 Entity Framework 6.1 模型。 当我从我的上下文中创建一个业务对象,然后尝试添加附件,然后 SaveChanges() 没有任何反应。有追踪模式吗?或者我可以打开的东西,看看幕后到底发生了什么。
简单的例子:
var fb = _context.Business.Create();
//fb.Id exists and is an int but it is auto incr in the db
fb.Name = ub.ACCOUNT_NAME;
fb.ServiceManager = ub.SERVICE_MANAGER;
fb.AccountManager = ub.ACCOUNT_MANAGER;
fb.SalesPerson = ub.SALESPERSON;
fb.Created = DateTime.UtcNow;
fb.Updated = DateTime.UtcNow;
_context.Add(fb);
_context.SaveChanges();
最佳答案
我发现捕获 EF 错误的最佳方法是重写 SaveChange 方法,如下所示。如果你有一个中心位置来恢复日志(比如 log4net),该函数将能够将它插入那里。
public partial class Business
{
/// <summary>Override the SaveChange to return better error messages</summary>
public override int SaveChanges()
{
try {
return base.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex) {
// Retrieve the error messages as a list of strings.
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
// Join the list to a single string.
var fullErrorMessage = string.Join("; ", errorMessages);
// Combine the original exception message with the new one.
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
// Add some logging with log4net here
// Throw a new DbEntityValidationException with the improved exception message.
throw new System.Data.Entity.Validation.DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
}
关于c# - EntityFramework 上下文中的 SaveChanges() 静默失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24499452/