【问题标题】:Unit tests connectionstring error单元测试连接字符串错误
【发布时间】:2011-08-01 14:39:27
【问题描述】:

我在 MVC 应用程序中工作。我的上下文类中有这个:

    public ProductsContext()
        : base("ProductyDB")
    {
        Database.SetInitializer<ProductsContext>(null);
    }

我的 web.config 连接字符串如下所示:

<add 
      name="ProductyDB"
      providerName="System.Data.SqlClient"
      connectionString="Data Source=.\SQLSERVER2008R2;Initial Catalog=ProductyDB;Integrated Security=True"/>

它在 MVC 应用程序中运行良好,但是一旦我在从这个 MVC 应用程序添加到这个解决方案的新单元测试项目中使用实体和函数,我就会得到像 tblProduct not available 这样的错误。

临时解决方法:如果我在 ProductsContext 中评论以下行:

公共 ProductsContext() : base("ProductyDB") { Database.SetInitializer(null); }

并将我的 web.config 连接字符串名称更改为 ProductsContext,它可以工作。

【问题讨论】:

  • 我的猜测是您的单元测试应用程序没有包含连接字符串的 app.config...您使用什么进行单元测试?
  • 我在单元测试项目中添加了一个 app.config 并在其中包含连接字符串,例如:
  • 这个问题接近你的[1]:stackoverflow.com/questions/9471148/…

标签: asp.net asp.net-mvc-3


【解决方案1】:

我遇到了与此类似的问题,结果证明我在 DbContext 类声明中设置了一个过时/不正确的表名。可能是一个独特的错误,但我的代码在除单元测试之外的所有内容中都能正常工作。

public ProductsContext()
    : base("ProductyDB") //This pointed at the wrong database name
{
    Database.SetInitializer<ProductsContext>(null);
}

我以为你应该输入的是 ConnectionString 名称,但实际上是你传入的 Initial Catalog

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 2013-02-11
    相关资源
    最近更新 更多