2017-04-10 52 views
1

我有一個C#應用程序,我正在嘗試使用LocalDB。截至目前,當我啓動我的應用程序時,我受到這個錯誤的迎接。'本地數據庫運行時:無法創建命名實例

Cannot create named instance. 

The parameter for the LocalDB Instance API method is incorrect. Consult the 
API documentation. 

我的App.config看起來像這樣。

<system.data.localdb> 
    <!-- I saw this on another website, I'm not sure if it's neeed or not.--> 
    <localdbinstances> 
    <add name="MSSQLLocalDB" version="mssqllocaldb" /> 
    </localdbinstances> 
</system.data.localdb> 
<connectionStrings> 
<add name="DiaProdConnection" 
    connectionString="Data Source=(localdb)\MSSQLLocalDB;AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf;Integrated Security=True;MultipleActiveResultSets=True" 
    providerName="System.Data.SqlClient" /> 
</connectionStrings> 
<entityFramework> 
    <defaultConnectionFactory 
     type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> 
<providers> 
    <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> 
</providers> 

當我運行Sqllocaldb.exe版本,我得到下面的輸出。

..> SqlLocalDB.exe versions 
    Microsoft SQL Server 2012 (11.0.3000.0) 
    Microsoft SQL Server 2014 (12.0.4459.0) 
    Microsoft SQL Server 2016 (13.0.1601.5) 

理想情況下,應用程序會啓動,當它看到db不存在時,它會創建它。

下面的代碼行可以在開發中使用,但是如果我的測試系統上有失敗的SQLLocalDB 2014版本,這就是我決定使用新字符串的原因。此外,鄉親們說舊字符串已棄用,並且僅適用於2012年。

<add name="DiaProdConnection" connectionString="data source=(localdb)\v11.0;initial catalog=DiaDb;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework;Connection Timeout=15;Connection Lifetime=0;Min Pool Size=10;Max Pool Size=20;Pooling=true;" providerName="System.Data.SqlClient" /> 

任何幫助,非常感謝。

+0

與2012數據庫一起使用的代碼有'connectionString ='data source =(localdb)\ ** v11.0 **'。您可以從包含的內容中瞭解到SQL Server 2012是版本11. SQL Server 2014是版本12.此外,我會將''更改爲' Jason

回答

1

SOLUTION:

  1. 清除火災所有非SQL 2014的LocalDB以上實例的計算機。在撰寫本文時,我正在使用SQL-2014版本。

  2. 使App.Config中的EF連接xml看起來像這樣。

    <system.data.localdb> 
        <localdbinstances> 
        <add name="MyNamedInstance" version="12.0" /> 
        </localdbinstances> 
    </system.data.localdb> 
    <connectionStrings> 
        <add name="DiaProdConnection" 
         connectionString="Data Source=(localdb)\MyNamedInstance;Initial 
         Catalog=MovieDB;Integrated 
         Security=True;AttachDbFilename=|DataDirectory|MovieDB.mdf" 
         providerName="System.Data.SqlClient" /> 
    </connectionStrings> 
    
  3. 很多例子都會有這個字段| DataDirectory |在他們的連接字符串。不幸的是,他們不會告訴你的是,該字符串不是框架已知的特殊字符串,而是您必須分配和設置自己的變量。爲此,我在我的應用程序的入口處調用此代碼。

    AppDomain.CurrentDomain.SetData(「DataDirectory」, Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));

請記住,如果DB存在於系統中但位於不同位置,則連接器將引發錯誤。

運行

Sqllocaldb.exe i 

應該幫助你查看是否有實例存在,並從那裏是否需要被刪除,你可以決定。

我很害怕文檔對錯誤有多糟糕,以及整個事情似乎令人厭惡。