【发布时间】:2014-07-30 23:05:29
【问题描述】:
首先在 Entity Framework 6 中使用代码,我想在我的 DbContext 中记录连接到服务器的失败。我可以覆盖 SaveChanges 并在那里捕获任何错误。那部分效果很好。但是,对于在我的一个公开集上运行的查询,我看不到在 DbContext 中的何处捕获异常。可以在 DbContext 内部捕获这些内容吗?这是我的调用堆栈。我可以覆盖此堆栈中的任何方法吗?
EntityFramework.SqlServer.dll!System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute<System.Data.Entity.Core.Objects.ObjectResult<Asi.Server.History.DBOs.LogSourceDbo>>(System.Func<System.Data.Entity.Core.Objects.ObjectResult<Asi.Server.History.DBOs.LogSourceDbo>> operation) + 0xfd bytes
EntityFramework.dll!System.Data.Entity.Core.Objects.ObjectQuery<Asi.Server.History.DBOs.LogSourceDbo>.GetResults(System.Data.Entity.Core.Objects.MergeOption? forMergeOption) + 0x286 bytes
EntityFramework.dll!System.Data.Entity.Core.Objects.ObjectQuery<Asi.Server.History.DBOs.LogSourceDbo>.System.Collections.Generic.IEnumerable<T>.GetEnumerator.AnonymousMethod__0() + 0x45 bytes
EntityFramework.dll!System.Data.Entity.Internal.LazyEnumerator<Asi.Server.History.DBOs.LogSourceDbo>.MoveNext() + 0x45 bytes
System.Core.dll!System.Linq.Enumerable.SingleOrDefault<Asi.Server.History.DBOs.LogSourceDbo>(System.Collections.Generic.IEnumerable<Asi.Server.History.DBOs.LogSourceDbo> source) + 0x139 bytes
EntityFramework.dll!System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.GetElementFunction.AnonymousMethod__2<Asi.Server.History.DBOs.LogSourceDbo>(System.Collections.Generic.IEnumerable<Asi.Server.History.DBOs.LogSourceDbo> sequence) + 0x54 bytes
EntityFramework.dll!System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle<Asi.Server.History.DBOs.LogSourceDbo>(System.Collections.Generic.IEnumerable<Asi.Server.History.DBOs.LogSourceDbo> query, System.Linq.Expressions.Expression queryRoot) + 0x6c bytes
EntityFramework.dll!System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute<Asi.Server.History.DBOs.LogSourceDbo>(System.Linq.Expressions.Expression expression) + 0xc6 bytes
EntityFramework.dll!System.Data.Entity.Internal.Linq.DbQueryProvider.Execute<Asi.Server.History.DBOs.LogSourceDbo>(System.Linq.Expressions.Expression expression) + 0x9c bytes
System.Core.dll!System.Linq.Queryable.SingleOrDefault<Asi.Server.History.DBOs.LogSourceDbo>(System.Linq.IQueryable<Asi.Server.History.DBOs.LogSourceDbo> source, System.Linq.Expressions.Expression<System.Func<Asi.Server.History.DBOs.LogSourceDbo,bool>> predicate) + 0x120 bytes
【问题讨论】:
-
您可以创建和注册自定义执行策略,而不是使用 DefaultSqlExecutionStrategy(这是默认设置)。 EF 包含用于 Azure 的执行策略,它捕获异常并重试所选错误的查询,因此它应该为您提供有关如何实现此功能的提示...
-
替换执行策略的计划几乎行得通:我只是看不到如何在执行策略中获取当前的 DbContext 实例。
-
我认为您无法直接从执行策略访问上下文,因为它在非常低的级别上运行。如果您只想将它记录到数据库中,您可以尝试创建一个新的上下文实例以将错误保存到数据库中。
标签: c# entity-framework dbcontext overriding