3

我正在使用 asp.net MVC 框架并使用 EntityFramework 连接到数据库。有时在连接到数据库时出现超时错误。这些错误非常罕见。

System.Data.Entity.Infrastructure.DbUpdateException:
 An error occurred while updating the entries. See the inner exception for details. ---> System.Data.UpdateException: An error occurred while updating the entries. 
See the inner exception for details. ---> System.Data.SqlClient.SqlException:
Timeout expired. The timeout period elapsed prior to 
completion of the operation or the server is not responding.

var myList = new List<MyConnection>();
using (var db = new MyDb())
            {
                var activeConns = db.Connections
                                    .Where(c => c.Key == tKey)
                                    .Where(c => c.IsActive)
                                    .ToList();
                if (activeConns.Count > 0)
                {
                    //Some custom logic
         myList.add(conn);
                }

            return myList;
        }

我没有设置任何连接超时时间。使用实体框架时是否有任何最佳实践?

我怎样才能人为地产生这种缺陷,以便我可以测试我们的软件?

4

2 回答 2

0

我们在代码库中处理此类事情的方式是使用模拟对象——允许我们用仅用于测试的假实现替换真实实现(例如,数据库)。

从客户端的角度来看,伪造的行为相同,但我们可以更好地控制测试错误之类的行为(例如,在第 5 次请求时抛出超时错误)。

模拟实体框架上下文是另一个 SO 问题,它更详细地介绍了如何设置它,特别是针对 EntityFramework。

于 2014-01-15T08:22:30.067 回答
0

您可能需要使用反射来抛出 SQL 超时异常。查看这篇文章以获得帮助: http ://blog.developers.ba/post/2009/03/08/SqlException-class-doesnt-have-public-constructor.aspx

于 2014-01-15T08:26:58.727 回答