Question

I use entity framework 6 code first.

At the moment I have a database for production. I want to add a different database for tests. How do I do that?

Do I need another connection string in my tests project?

What should be the difference between the two connection strings?

I tried copying the connection string and change the Catalog name but it results in mapping to the same database.

Please help me understand each part of the connection string in general

Thanks

1
2
4/10/2016 4:20:33 PM

Popular Answer

Using local db in the local test environment

You can use localdb for your testing environment. Localdb is a file based database on your local development system which does not need a server to run but behaves like an SQL Server from your applications point of view.

I can describe the steps I would perform in Visual Studio 2013:

  • Open the "SQL Server Object Explorer" window
  • Expand the entry beginning with (localdb)v.11.0
  • Right click on "Database" and click "Add new Database" from the context menu
  • On my System this will create a localdb (mdf file) in my users folder e.g. C:\Users\USERNAME\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\v11.0
  • After the database is created you can create the tables in your localdb matching your live environment using scripts. For example, you can use SQL Server Management Studio to export the table structure (database -> Tasks -> Generate Scripts)
  • To get the connection string: Open the context menu of the database (still in Visual Studio SQL Server Object Explorer) and choose "Properties".
  • In the properties Windows locate the "Connection string" property and copy its value. Example: Data Source=(localdb)\v11.0;Initial Catalog=DATABASENAME;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
  • Use this Connection string to create a new connectrion string in your web.config or app.config within the connectionStrings element. Put the value in the connectionString attribute. Do not change the providerName attribute.

     <connectionStrings>
       <add name="ConnectionName" connectionString="..." providerName="System.Data.SqlClient" />    
    </connectionStrings>
    
  • Use that connection string name in your DbContext derived class:

    public class YourDbContext : DbContext
    {
        public YourDbContext() : base("ConnectionName")
        {        
        }
    }
    
7
4/12/2016 6:32:40 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow