Search code examples
c#.netentity-frameworklocaldb

Connecting to localDb in a unit test throws exception


I have a VS2013 project that talks to a Sql Server database, using EF6.1. To date, I've been running some automated tests using the Effort in-memory database.

I'm experimenting with using Sql Server's LocalDb, instead, and I'm running into problems I don't understand.

  • From with VS's Server Explorer, I created a new connection to a LocalDb database, and through it I created a new database, then
  • I brought up the properties window on the database, in Server Explorer, and copied the Connecting String to my clipboard, then
  • I pasted this connection string into the ConnectionString element of my test assembly's App.config,
  • I ran one of the tests.

I get:

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

My connection string is simple:

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

And my code is equally simple:

[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);
    }
}

Any ideas as to what might be going wrong?


Solution

  • You have specified the provider as System.Data.EntityClient instead of System.Data.SqlClient. Both of those require different connection string formats.

    A good source for working out what to use is http://www.connectionstrings.com