0

i am working on a web api and i need to have a local db in the App_Data folder, I'm using Entity Framework Code First but it does not create database in the App_Data

Here is my connection string :

  <connectionStrings>
    <add name="TestDBContext"
         connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=TestDB;Integrated Security=True;MultipleActiveResultSets=True;AttachDBFilename=|DataDirectory|TestDB.mdf;User Instance=True"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

i used show all file in the project menu and bla bla bla

but database is being create in

C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA

how do i fix this?

Hooman Limouee
  • 1,143
  • 2
  • 21
  • 43
  • Add `AttachDbFileName=` section inside the connection string. [Reference](https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx#localdb) – Ivan Stoev Jan 24 '17 at 18:55

3 Answers3

1

Yes, that is the default. Two ways to fix:

1) Add connection string to constructor of your context:

public ApplicationDbContext()
        : base("TestDBContext") { }

2) Add a default connection factory to your config:

<entityFramework> 
  <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"> 
    <parameters> 
      <parameter value="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=TestDB;Integrated Security=True;MultipleActiveResultSets=True;AttachDBFilename=|DataDirectory|TestDB.mdf;User Instance=True" /> 
    </parameters> 
  </defaultConnectionFactory> 
</entityFramework>

See https://msdn.microsoft.com/en-us/data/jj556606

Steve Greene
  • 12,029
  • 1
  • 33
  • 54
0

Typically you need to change the settings in the app config to be 'AttachDbFileName' else it defaults to a SQL Server Express instance. Usually you can just set the mode to attached and fix this:

<add name="ConnectionStringName"
     providerName="System.Data.SqlClient"
     connectionString="Data Source=(LocalDB)\v11.0;AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf;InitialCatalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True" />

Here is an MS page on connections for you too: https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx#sqlce\

Although I would SERIOUSLY suggest if this is not a small compact app that will have small growth you do not do an attached database. This is just a bad idea for deployments of large scale apps and a bad practice in general unless you know your database will mostly always be small. Just my two cents though.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
djangojazz
  • 14,131
  • 10
  • 56
  • 94
0

Problem solved by installing Sql LocalDB

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Hooman Limouee
  • 1,143
  • 2
  • 21
  • 43