【问题标题】:Connecting to localDb in a unit test throws exception在单元测试中连接到 localDb 会引发异常
【发布时间】:2014-07-25 21:41:54
【问题描述】:

我有一个使用 EF6.1 与 Sql Server 数据库对话的 VS2013 项目。迄今为止,我一直在使用 Effort 内存数据库运行一些自动化测试。

我正在尝试使用 Sql Server 的 LocalDb,但遇到了我不理解的问题。

  • 通过 VS 的服务器资源管理器,我创建了一个到 LocalDb 数据库的新连接,并通过它创建了一个新数据库,然后
  • 我在服务器资源管理器中打开了数据库的属性窗口,并将连接字符串复制到我的剪贴板,然后
  • 我将此连接字符串粘贴到我的测试程序集 App.config 的 ConnectionString 元素中,
  • 我进行了一项测试。

我明白了:

System.ArgumentException: "Keyword not supported: 'data source'".

我的连接字符串很简单:

<add name="MyDbContext" 
    connectionString="Data Source=(localdb)\v11.0;Initial Catalog=localDb;Integrated Security=True" 
    providerName="System.Data.EntityClient"
    />

我的代码同样简单:

[TestClass]
public class TestCustomers
{
    private MyDbContext myDbContext = null;

    private IEnumerable<customer> defaultCustomers = new []
        {
            new customer{customerid = "Customer 1"},
            new customer{customerid = "Customer 2"},
            new customer{customerid = "Customer 3"},
        };

    [TestInitialize]
    public void init()
    {
        this.myDbContext = new MyDbContext();

        foreach (var customer in this.defaultCustomers)
            this.myDbContext.customers.Add(customer);
        this.myDbContext.SaveChanges();
    }

    [TestMethod]
    public void testAllCustomers()
    {
        var customers = this.myDbContext.customers;
        var customerList = customers.ToList();
        Assert.IsTrue(customerList.Count == 3);
    }
}

关于可能出现什么问题的任何想法?

【问题讨论】:

  • EF 连接字符串是不同的格式。见这里:stackoverflow.com/questions/1404268/…
  • 那个问题有正确的答案。我需要用 localDb 属性页给我的内容替换 EF 连接字符串的“提供者连接字符串”部分,而不是替换整个 EF 连接字符串。

标签: c# .net entity-framework localdb


【解决方案1】:

您已将提供程序指定为System.Data.EntityClient 而不是System.Data.SqlClient。两者都需要不同的连接字符串格式。

确定使用什么的好来源是http://www.connectionstrings.com

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 2020-01-13
    • 1970-01-01
    相关资源
    最近更新 更多