c# - 在单元测试中连接到 localDb 会抛出异常

标签 c# .net entity-framework localdb

我有一个使用 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);
    }
}

关于可能出现的问题有什么想法吗?

最佳答案

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

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

关于c# - 在单元测试中连接到 localDb 会抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24964943/

相关文章:

c# - 如何让TableEntity序列化非公共(public)属性?

c# - 检查变量以在运行时 C# 设置类值

c# - 如何以不错的速度在 C#/WinForms 中绘图?

c# - 在 Windows Phone 8.1 中调用电话

c# - 集成到 VS2008 时的 antlr c# 错误

c# - 从 Entity Framework .NET 返回父子的多个孙子

c# - 使用名称单独超链接创建 Gridview

c# - 加载大量要在 WrapPanel 中显示的图像

c# - AsNoTracking() 的全局设置?

c# - 为 EF 6.x 和 EF Core 重用 EF 实体