local DB error 50 [duplicate] - c#

I am trying to build an ASP.NET MVC 5 Web Application which has a MyDatabase.mdf file in the App_Data folder. I have SQL Server 2014 Express installed with a LocalDb instance. I can edit the database tables using the Server Explorer, however when I debug the application and go to a page where the database is needed I get the following error.
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.
So I looked in the Event Viewer under Application and only see one Warning over and over again.
The directory specified for caching compressed content C:\Users\User1\AppData\Local\Temp\iisexpress\IIS Temporary Compressed Files\Clr4IntegratedAppPool is invalid. Static compression is being disabled.
So I tried rebooting the server, still no go. Same error 50 as before.
I have created an class under Models where I have a class called Post.
namespace MyApplication.Models
{
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
public class MyDatabase : DbContext
{
public DbSet<Post> Posts { get; set; }
}
}
I also have a Controller setup to list the posts from MyDatabase.
namespace MyApplication.Controllers
{
public class PostsController : Controller
{
private MyDatabase db = new MyDatabase();
// GET: Posts
public ActionResult Index()
{
return View(db.Posts.ToList());
}
}
In my web.config file the connection string looks like this...
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=(LocalDB)\v12.0;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
I've tried the suggestion posted here but it didn't work. Also tried this.
I also notice that the MyDatabase instance gets disconnected after I start running the application. If I refresh the database using Server Explorer in Visual Studio I can view the tables.
How is it that I can connect to the database and edit it within Visual Studio 2013 but when I debug the application it cannot connect to the database?

Breaking Changes to LocalDB: Applies to SQL 2014; take a look over this article and try to use (localdb)\mssqllocaldb as server name to connect to the LocalDB automatic instance, for example:
<connectionStrings>
<add name="ProductsContext" connectionString="Data Source=(localdb)\mssqllocaldb;
...
The article also mentions the use of 2012 SSMS to connect to the 2014 LocalDB. Which leads me to believe that you might have multiple versions of SQL installed - which leads me to point out this SO answer that suggests changing the default name of your LocalDB "instance" to avoid other version mismatch issues that might arise going forward; mentioned not as source of issue, but to raise awareness of potential clashes that multiple SQL version installed on a single dev machine might lead to ... and something to get in the habit of in order to avoid some.
Another thing worth mentioning - if you've gotten your instance in an unusable state due to tinkering with it to try and fix this problem, then it might be worth starting over - uninstall, reinstall - then try using the mssqllocaldb value instead of v12.0 and see if that corrects your issue.

Running this:
sqllocaldb create "v12.0"
From cmd prompt solved this for me...

I usually fix this errore following this msdn blog post Using LocalDB with Full IIS
This requires editing applicationHost.config file which is usually located in C:\Windows\System32\inetsrv\config. Following the instructions from KB 2547655 we should enable both flags for Application Pool ASP.NET v4.0, like this:
<add name="ASP.NET v4.0" autoStart="true" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated">
<processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />
</add>

To begin - there are 4 issues that could be causing the common LocalDb SqlExpress Sql Server connectivity errors SQL Network Interfaces, error: 50 - Local Database Runtime error occurred, before you begin you need to rename the v11 or v12 to (localdb)\mssqllocaldb
Possible Issues
You don't have the services running
You don't have the firelwall ports here
configured
Your install has and issue/corrupt (the steps below help give you a nice clean start)
You did not rename the V11 or 12 to mssqllocaldb
\\ rename the conn string from v12.0 to MSSQLLocalDB -like so->
`<connectionStrings>
<add name="ProductsContext" connectionString="Data Source= (localdb)\mssqllocaldb;
...`
I found that the simplest is to do the below - I have attached the pics and steps for help.
First verify which instance you have installed, you can do this by checking the registry& by running cmd
1. `cmd> Sqllocaldb.exe i`
2. `cmd> Sqllocaldb.exe s "whicheverVersionYouWantFromListBefore"`
if this step fails, you can delete with option `d` cmd> Sqllocaldb.exe d "someDb"
3. `cmd> Sqllocaldb.exe c "createSomeNewDbIfyouWantDb"`
4. `cmd> Sqllocaldb.exe start "createSomeNewDbIfyouWantDb"`
ADVANCED Trouble Shooting Registry configurations
Edit 1, from requests & comments: Here are the Registry path for all versions, in a generic format to track down the registry
Paths
// SQL SERVER RECENT VERSIONS
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\(instance-name)
// OLD SQL SERVER
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MSSQLServer
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer
// SQL SERVER 6.0 and above.
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\MSDTC
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SQLExecutive
// SQL SERVER 7.0 and above
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SQLServerAgent
HKEY_LOCAL_MACHINE\Software\Microsoft\Microsoft SQL Server 7
HKEY_LOCAL_MACHINE\Software\Microsoft\MSSQLServ65
Searching
SELECT registry_key, value_name, value_data
FROM sys.dm_server_registry
WHERE registry_key LIKE N'%SQLAgent%';
or Run this in SSMS Sql Management Studio, it will give a full list of all installs you have on the server
DECLARE #SQL VARCHAR(MAX)
SET #SQL = 'DECLARE #returnValue NVARCHAR(100)'
SELECT #SQL = #SQL + CHAR(13) + 'EXEC master.dbo.xp_regread
#rootkey = N''HKEY_LOCAL_MACHINE'',
#key = N''SOFTWARE\Microsoft\Microsoft SQL Server\' + RegPath + '\MSSQLServer'',
#value_name = N''DefaultData'',
#value = #returnValue OUTPUT;
UPDATE #tempInstanceNames SET DefaultDataPath = #returnValue WHERE RegPath = ''' + RegPath + '''' + CHAR(13) FROM #tempInstanceNames
-- now, with these results, you can search the reg for the values inside reg
EXEC (#SQL)
SELECT InstanceName, RegPath, DefaultDataPath
FROM #tempInstanceNames
Trouble Shooting Network configurations
SELECT registry_key, value_name, value_data
FROM sys.dm_server_registry
WHERE registry_key LIKE N'%SuperSocketNetLib%';

An instance might be corrupted or not updated properly.
Try these Commands:
C:\>sqllocaldb stop MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" stopped.
C:\>sqllocaldb delete MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" deleted.
C:\>sqllocaldb create MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" created with version 13.0.1601.5.
C:\>sqllocaldb start MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" started.

maybe this error came because this version of Sql Server is not installed
connectionString="Data Source=(LocalDB)\v12.0;....
and you don't have to install it
the fastest fix is to change it to any installed version you have
in my case I change it from v12.0 to MSSQLLocalDB

Final Solution for this problem is below :
First make changes in applicationHost config file. replace below string setProfileEnvironment="false" TO setProfileEnvironment="true"
In your database connection string add below attribute : Integrated Security = SSPI

I ran into the same problem. My fix was changing
<parameter value="v12.0" />
to
<parameter value="mssqllocaldb" />
into the "app.config" file.

All PLEASE note what Tyler said
Note that if you want to edit this file make sure you use a 64 bit text editor like notepad. If you use a 32 bit one like Notepad++ it will automatically edit a different copy of the file in SysWOW64 instead. Hours of my life I won't get back

In my case, we had several projects in one solution and had selected a different start project than in the package manager console when running the "Update-Database" Command with Code-First Migrations.
Make sure to select the proper start project.

I have solved above problem Applying below steps
And after you made thses changes, do following changes in your web.config
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v12.0;AttachDbFilename=|DataDirectory|\aspnet-Real-Time-Commenting-20170927122714.mdf;Initial Catalog=aspnet-Real-Time-Commenting-20170927122714;Integrated Security=true" providerName="System.Data.SqlClient" />

My issue was that i had multiple versions of MS SQL express installed. I went to installation folder C:\Program Files\Microsoft SQL Server where i found
3 versions of it. I deleted 2 folders, and left only MSSQL13.SQLEXPRESS which solved the problem.

Related

C# application deployment issue with .mdf database

I am working on a C# database application for learning and I'm trying to deploy it on client machine and getting connection problem.
//NOTE: path and database variables have correct info because it works on my dev machine
"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=" + path + "\\" + databaseName + ";Integrated Security=True"
I am using Install Shield for creating setup and tried Advance Installer also.
On the other test machine I have installed:
.Net Framework 4.5.2
SQLLocalDB.msi (x64 bit)
Lastly, I installed my deployed setup file and I was getting an Exception:
System.Data.SqlClient.SqlException (0x80131904). A network related or instance-specific error occured while establishing a connection to SQL server.
The server was not found or not accessible.
Localdatabase Runtime error occured.
I also tried these in Connection String: (found in similar question on stackoverflow)
localhost
localhost\\SQLExpress
.\\SQLExpress
But none of this work for me.
NOTE:
My LocalDB connection string is working on dev machine.
Using Visual Studio 2015 Enterprise
PS: What I am trying to learn is a way to create an installer which installs some per-requeisites like .Net Framework, LocalDB etc and can run database based application on client machines without installing SQL Server separately. I am not sure if the .mdf way is the good fit for this or not.
I would suggest you to use SQLite Database because the process and function are almost similar. And the deployment is super easy; it just requires few DLLs to make it work.
Guideline:
First you will need System.Data.SQLite library and then needs to add System.Data.SQLite.dll as a reference in your project. Keep in mind that SQLite.Interop.dll also needs to be in your executables directory but doesn’t need to be added as a reference in your project.
Moreover, if your application is targeting Any CPU it is likely that you will get an exception. So make sure to navigate to Project properties -> Build and set the Platform target to the bit version of the System.Data.SQLite.dll binary you have downloaded.
As you are beginner so here is the step by step guideline along with sample code.
Steps:
Navigate to: Tools > NuGet Package Manager > Manage NuGet Packages for Solution
Search For: SQLite
Select System.Data.SQLite (would be first result)
Click on Install
Import library
using System.Data.SQLite;
The connection is ready and here is the Sample Code:
System.Data.SQLite.SQLiteConnection.CreateFile("sqlite.db3");
using(System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("data source=sqlite.db3")){
using(System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand(conn)){
conn.Open();
cmd.CommandText = #"CREATE TABLE IF NOT EXISTS
[persons](
[id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
[name] VARCHAR(50) NULL
)";
cmd.ExecuteNonQuery();
cmd.CommandText = "INSERT INTO [persons] (name) values('Atlas')";
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT * FROM [persons]";
using(System.Data.SQLite.SQLiteDataReader reader = cmd.ExecuteReader()){
while(reader.Read()){
MessageBox.Show(reader["name"].ToString());
}
conn.Close();
}
}
}
Tips:
always use try/catch block for database operations
If you don't prefer to use NuGet Package Manager then you can download library from here
Hope this helps! :)
Does one of these help?
Attach a database file on connect to a local SQL Server Express instance
Server=.\SQLExpress;AttachDbFilename=C:\MyFolder\MyDataFile.mdf;Database=dbname;
Trusted_Connection=Yes;
Attach a database file, located in the data directory, on connect to a local SQL Server Express instance
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname;
Trusted_Connection=Yes;

Cannot create database with Code-First

I am using Visual Studio 2015, Entity Framework v6, and SQL Server 2016 Express. In the past I created a database using a SqlConnection and SqlCommand and stuff the SQL into a string.
Now, I am teaching myself EF6 on Entity Framework Tutorial. On the simple code-first example (very simple), I literally copy and paste my code but still do not see the database created in SSMS. Neither does my code throw me any error.
Instead of pasting the code, I did a screenshot. I hope someone can point out what I am or the tutorial is missing.
[EDIT]
Following Sampath's suggestion, I end up getting the following error:
[EDIT - Solved, sort of]
I apply the same code to another machine of same setup and the code works. So I suspect there are some corruption in the SQL Server or perhaps some registry is incorrect. I uninstall EVERY SQL Server version and related tools, delete all folders and files manually, then freshly reinstall SQL Server Express 2016 and tools. Then my code works.
I don't see this as a solution, but if someone can suggest what may have cause this problem I will try to recreate it or post a real solution to it.
You have to give the connection string name on the web.config file as shown below.
Context :
public SchoolContext(): base("MySchoolDB")
{
}
App.config file
<add name="MySchoolDB" connectionString="Server=localhost;
Database=YourDBName;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
You can get more details here : Database Initialization
You have to add entity to your database after configuring connection string, then DBContext will create database. Here is a connection string example:
<add name="Name" connectionString="Data Source=.; Initial Catalog=yourdbName; Integrated Security=True; MultipleActiveResultSets=True;"
providerName="System.Data.SqlClient" />

Error when connecting to local SQL Server database [duplicate]

I am trying to build an ASP.NET MVC 5 Web Application which has a MyDatabase.mdf file in the App_Data folder. I have SQL Server 2014 Express installed with a LocalDb instance. I can edit the database tables using the Server Explorer, however when I debug the application and go to a page where the database is needed I get the following error.
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.
So I looked in the Event Viewer under Application and only see one Warning over and over again.
The directory specified for caching compressed content C:\Users\User1\AppData\Local\Temp\iisexpress\IIS Temporary Compressed Files\Clr4IntegratedAppPool is invalid. Static compression is being disabled.
So I tried rebooting the server, still no go. Same error 50 as before.
I have created an class under Models where I have a class called Post.
namespace MyApplication.Models
{
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
public class MyDatabase : DbContext
{
public DbSet<Post> Posts { get; set; }
}
}
I also have a Controller setup to list the posts from MyDatabase.
namespace MyApplication.Controllers
{
public class PostsController : Controller
{
private MyDatabase db = new MyDatabase();
// GET: Posts
public ActionResult Index()
{
return View(db.Posts.ToList());
}
}
In my web.config file the connection string looks like this...
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=(LocalDB)\v12.0;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
I've tried the suggestion posted here but it didn't work. Also tried this.
I also notice that the MyDatabase instance gets disconnected after I start running the application. If I refresh the database using Server Explorer in Visual Studio I can view the tables.
How is it that I can connect to the database and edit it within Visual Studio 2013 but when I debug the application it cannot connect to the database?
Breaking Changes to LocalDB: Applies to SQL 2014; take a look over this article and try to use (localdb)\mssqllocaldb as server name to connect to the LocalDB automatic instance, for example:
<connectionStrings>
<add name="ProductsContext" connectionString="Data Source=(localdb)\mssqllocaldb;
...
The article also mentions the use of 2012 SSMS to connect to the 2014 LocalDB. Which leads me to believe that you might have multiple versions of SQL installed - which leads me to point out this SO answer that suggests changing the default name of your LocalDB "instance" to avoid other version mismatch issues that might arise going forward; mentioned not as source of issue, but to raise awareness of potential clashes that multiple SQL version installed on a single dev machine might lead to ... and something to get in the habit of in order to avoid some.
Another thing worth mentioning - if you've gotten your instance in an unusable state due to tinkering with it to try and fix this problem, then it might be worth starting over - uninstall, reinstall - then try using the mssqllocaldb value instead of v12.0 and see if that corrects your issue.
Running this:
sqllocaldb create "v12.0"
From cmd prompt solved this for me...
I usually fix this errore following this msdn blog post Using LocalDB with Full IIS
This requires editing applicationHost.config file which is usually located in C:\Windows\System32\inetsrv\config. Following the instructions from KB 2547655 we should enable both flags for Application Pool ASP.NET v4.0, like this:
<add name="ASP.NET v4.0" autoStart="true" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated">
<processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />
</add>
To begin - there are 4 issues that could be causing the common LocalDb SqlExpress Sql Server connectivity errors SQL Network Interfaces, error: 50 - Local Database Runtime error occurred, before you begin you need to rename the v11 or v12 to (localdb)\mssqllocaldb
Possible Issues
You don't have the services running
You don't have the firelwall ports here
configured
Your install has and issue/corrupt (the steps below help give you a nice clean start)
You did not rename the V11 or 12 to mssqllocaldb
\\ rename the conn string from v12.0 to MSSQLLocalDB -like so->
`<connectionStrings>
<add name="ProductsContext" connectionString="Data Source= (localdb)\mssqllocaldb;
...`
I found that the simplest is to do the below - I have attached the pics and steps for help.
First verify which instance you have installed, you can do this by checking the registry& by running cmd
1. `cmd> Sqllocaldb.exe i`
2. `cmd> Sqllocaldb.exe s "whicheverVersionYouWantFromListBefore"`
if this step fails, you can delete with option `d` cmd> Sqllocaldb.exe d "someDb"
3. `cmd> Sqllocaldb.exe c "createSomeNewDbIfyouWantDb"`
4. `cmd> Sqllocaldb.exe start "createSomeNewDbIfyouWantDb"`
ADVANCED Trouble Shooting Registry configurations
Edit 1, from requests & comments: Here are the Registry path for all versions, in a generic format to track down the registry
Paths
// SQL SERVER RECENT VERSIONS
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\(instance-name)
// OLD SQL SERVER
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MSSQLServer
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer
// SQL SERVER 6.0 and above.
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\MSDTC
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SQLExecutive
// SQL SERVER 7.0 and above
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SQLServerAgent
HKEY_LOCAL_MACHINE\Software\Microsoft\Microsoft SQL Server 7
HKEY_LOCAL_MACHINE\Software\Microsoft\MSSQLServ65
Searching
SELECT registry_key, value_name, value_data
FROM sys.dm_server_registry
WHERE registry_key LIKE N'%SQLAgent%';
or Run this in SSMS Sql Management Studio, it will give a full list of all installs you have on the server
DECLARE #SQL VARCHAR(MAX)
SET #SQL = 'DECLARE #returnValue NVARCHAR(100)'
SELECT #SQL = #SQL + CHAR(13) + 'EXEC master.dbo.xp_regread
#rootkey = N''HKEY_LOCAL_MACHINE'',
#key = N''SOFTWARE\Microsoft\Microsoft SQL Server\' + RegPath + '\MSSQLServer'',
#value_name = N''DefaultData'',
#value = #returnValue OUTPUT;
UPDATE #tempInstanceNames SET DefaultDataPath = #returnValue WHERE RegPath = ''' + RegPath + '''' + CHAR(13) FROM #tempInstanceNames
-- now, with these results, you can search the reg for the values inside reg
EXEC (#SQL)
SELECT InstanceName, RegPath, DefaultDataPath
FROM #tempInstanceNames
Trouble Shooting Network configurations
SELECT registry_key, value_name, value_data
FROM sys.dm_server_registry
WHERE registry_key LIKE N'%SuperSocketNetLib%';
An instance might be corrupted or not updated properly.
Try these Commands:
C:\>sqllocaldb stop MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" stopped.
C:\>sqllocaldb delete MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" deleted.
C:\>sqllocaldb create MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" created with version 13.0.1601.5.
C:\>sqllocaldb start MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" started.
maybe this error came because this version of Sql Server is not installed
connectionString="Data Source=(LocalDB)\v12.0;....
and you don't have to install it
the fastest fix is to change it to any installed version you have
in my case I change it from v12.0 to MSSQLLocalDB
Final Solution for this problem is below :
First make changes in applicationHost config file. replace below string setProfileEnvironment="false" TO setProfileEnvironment="true"
In your database connection string add below attribute : Integrated Security = SSPI
I ran into the same problem. My fix was changing
<parameter value="v12.0" />
to
<parameter value="mssqllocaldb" />
into the "app.config" file.
All PLEASE note what Tyler said
Note that if you want to edit this file make sure you use a 64 bit text editor like notepad. If you use a 32 bit one like Notepad++ it will automatically edit a different copy of the file in SysWOW64 instead. Hours of my life I won't get back
In my case, we had several projects in one solution and had selected a different start project than in the package manager console when running the "Update-Database" Command with Code-First Migrations.
Make sure to select the proper start project.
I have solved above problem Applying below steps
And after you made thses changes, do following changes in your web.config
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v12.0;AttachDbFilename=|DataDirectory|\aspnet-Real-Time-Commenting-20170927122714.mdf;Initial Catalog=aspnet-Real-Time-Commenting-20170927122714;Integrated Security=true" providerName="System.Data.SqlClient" />
My issue was that i had multiple versions of MS SQL express installed. I went to installation folder C:\Program Files\Microsoft SQL Server where i found
3 versions of it. I deleted 2 folders, and left only MSSQL13.SQLEXPRESS which solved the problem.

Error in update-database command in code first migration

I am working on Desktop application in WPF and creating SqlRepository with LocalDB to store data. I am using following tools
Visual Studio 2013 Community with update 2
Entity Framework 6.1.2 for Code first migration
I have created local database with Microsoft SQL Server Database File (SqlClient) configuration. Database created successfully and below is connection string fetched from Sql
Data Source=(LocalDB)\v11.0;Initial Catalog=D:\USERS\USERNAME\DOCUMENTS\TestDatabase\testdb.MDF;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False
I am using same connection string in app.config. I can view database object in SQL Server Database explorer in Visual Studio. But when run update-database command in Nuget package manager console, I am getting below error:
A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (provider: SQL
Network Interfaces, error: 26 - Error Locating Server/Instance
Specified)
I had similar problem and fixed it when I changed the "start-up project" from another module to the module containing references to all other projects in the solution.
Right-click module >> click "Set as StartUp Project"
Diego's answer is correct.
This problem occurs when there is no connection string in project marked as startup project. Then EF tries to connect to some default database engine to perform update. In my case it tried to use express, and for some reason it couldn't connect. And the error was thrown.
Run your "update-database" with option "-Verbose". One of the lines there shows which StartUp project is used. Check your connection string in this project, or change the startup project to the one that has correct connection string. That solves the problem.
As explained in other answers, the problem usually comes from having the wrong Initial project in Package Manager Console.
In my case the console was ignoring the value I selected in the Default Project drop down list, and also the -StartUpProjectName parameter, and reproducing the wrong behavior of trying to connect to some default database engine, as Mikk's answer describes, in my case using a SqlExpress engine.
My problem was caused by a wrong solution configuration: if your solution has several projects and is meant to be run with the configuration option "Multiple startup projects", but you just downloaded it from your source code control repository, then it is possible that the default configuration option "Single startup project" is being applied to the solution (this config value usually is not checked-in in the source code control). In this case the Package Manager Console just ignores the startup project selected in its combo and just applies the default startup project in the solution, which may not have a connection string, as specified in Mikk's answer.
So I fixed it by changing the solution properties: Common properties / Startup project / Select Multiple startup projects instead of Single startup project, and after that the Package Manager Console would accept the Project name and update the right database.
I was able to solve this by adding parameters to the update-database command:
update-database -StartupProjectName MyApp.Web -ConnectionStringName MyAppConnectStringInWebConfig
I solved this error changing the initial project to the Entity Project.
Look:
Update-Database -Verbose
Using StartUp project 'SCVE.Web'. <-- this ir error
Using NuGet project 'SCVE.EntityFramework'.
A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (provider: SQL
Network Interfaces, error: 26 - Error Locating Server/Instance
Specified)
This error message informs you that it is not possible to connect to SQL Server. The possible reasons and their elimination is described below:
1) SQL Server is not started. Starting of it will allow you to see your SQL Server/instance in the drop-down list of available SQL Servers.
Go to the Start menu -> Control Panel -> Administration Tools ->
Services.
In the list of services find SQL Server (instance name, by
default it is EZPARTS5) and check its status, it must be Started
(if it is not started, then right click on SQL Server and select
Start from the context menu).
2) Firewall is blocking port 1433 (MSSQL standard port for connections). It can be disabled following the steps below:
Go to the Start menu -> Control Panel -> Administration Tools ->
Services.
Find Firewall service, it must be disabled (if it is not, then right
click the service and select Stop from the context menu).
Note: More information on this can be found on the official Microsoft site: Link
3) TCP/IP protocol is disabled for MSSQL protocols. To enable it, see the steps below:
Navigate to SQL Server Configuration Manager in the Start menu.
Specify settings for TCP/IP protocol in SQL Server Configuration
Manager.
Restart the computer.
Note: More information on this can be found on the official Microsoft site: Link
4) Make sure your database engine is configured to accept remote connections (If you are using centralized database):
Open SQL Server Management Studio.
Right click SQL Server instance -> Properties -> Connections ->
Check the Allow remote connections to this server box.
Go to the General section and check name of SQL Server specified in
the Name field.
5) If you are using a named SQL Server instance, make sure you are using that instance name in your connection strings. Usually the format needed to specify the database server is machinename\instancename.
6) Make sure your login account has access permission on the database you used during login.
Alternative:
If you still can’t get any connection, you may want to create a SQL account on the server, a corresponding SQL user on the database in question, and just use this username/password login data to connect to SQL Server.
Referred from this link
Try with this Connectionstring:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=D:\USERS\USERNAME\DOCUMENTS\TestDatabase\testdb.MDF;Initial Catalog=testdb;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
If you are trying to connect to Sql Server instead of localdb then make sure the default connection factory in web.config file is as below:
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=.\SQLEXPRESS2012; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
I had this same problem with a freshly created ASP.NET project.
First I tried to set the startup project as mentioned above. There was no startup project selected and I was unable to select one.
Ultimately I updated my Visual Studio from 2015 Update 1 to 2015 Update 3 and
update-database
executed without problems.
PM>Update-Database
error and solution which I did today in 4 hours.
I am very much new in .net coding, but yes in PHP I have 10+ years experience.
It took me 4 hours to solve this.
1.My first Mistake: I was not having Microsoft SQL Server 2019 in my laptop locally I was having this through AZURE which is not works for localhost, so I installed this locally after download, it took around 2 Hours.
2.Second changed mistake=
"DevConnection": "Server=localhost;Database=PaymentDetailDB;Trusted_Connection=True;MultipleActiveResultSets=True;"
then it works for me

SqlExpress LocalDb can't open file

I have two MDF files in a directory down the AppData/Local path. If I attempt to open them using LocalDb.
My connection string is of the form:
Data
Source=(localdb)\v11.0;AttachDbFilename="C:\Users\Anna\AppData\Local\CaseTrakker
Software\CTDynamoDisconnected\CTDynamoDisconnected_Data.mdf";Integrated
Security=True;Connect Timeout=10
I have a sample desktop application that attempts to connect to this MDF, and I get this exception:
System.Data.SqlClient.SqlException (0x80131904): Cannot open database
"C:\USERS\ANNA\APPDATA\LOCAL\CASETRAKKER
SOFTWARE\CTDYNAMODISCONNECTED\CTDYNAMODISCONNECTED_DATA.MDF" requested
by the login. The login failed. Login failed for user 'IMA\Anna'.
If I move this file to any other location, or rename it (even to a name that is longer), I am able to connect to it.
There appears to be something peculiar about this location or something.
One other odd thing: it worked last week. So far as I am aware, nothing has changed on my machine or my Domain Security.
I'm at a complete loss as to what else to even try. Ideas?
Can you check if there is anything interesting in the LocalDB instance log file? It is located by default in %localappdata%\Microsoft\Microsoft SQL Server Local DB\Instances\v11.0 folder.
One cause of this problem is if you go into your C:\Users\[username] folder and delete the MDF and LDF files. If you do this, then that's akin to doing the same thing to full-blown SQL Server. The server instance still thinks it has the databases but they're obviously not going to work.
A work-around to the problem is to change the database name in your connection string and it should just work.
To actually fix the problem, open up SQL Management Studio, connect to server (LocalDb)\v11.0 (likely with Windows Authentication) and you can detach these databases this way.
In my case I had that DB for a while and mistakenly deleted its MDF and LDF files.
To solve this, I opened SQL Management Studio and connected to (localdb)\MSSQLLocalDB using Windows Authentication then created manually a new empty DB with desired name like that in web.config connection string
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=myDb;Integrated Security=True;" providerName="System.Data.SqlClient" />

Categories