c# - EntityFramework 上下文中的 SaveChanges() 静默失败

标签 c# .net entity-framework entity-framework-6

我正在使用数据库“向导”设置中的 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/

相关文章:

c# - 使用日期条件从 Varchar Col 提取数据时出现问题

.net - 为什么 SSIS 在将数据从 Excel 传输到 CSV 时将最后一行保存为 NULL?

entity-framework - 重用包含 SqlFunctions.DatePart 的表达式

c# - 数据库优先与 POCO

c# - 单击时将参数传递到 ASP.Net Button 控件

c# - 如何在 WinForms 中更新 DataGridView

c# - 循环直到 TcpClient 响应完全读取

c# - 默认情况下 dbo 架构中的 EF 6 Code First __MigrationHistory

c# - 如何在 ODataQueryOptions 上启用 $expand 和 $select?

.net - .NET 是 "all COM underneath"吗?