Ivan Ivan - 3 months ago 59
ASP.NET (C#) Question

Creating a Connection String and Working with SQL Server LocalDB

I have problem when i try to connect to localdb from visual studio 15.
I have installed SQL Server Express 2016

I folowing this tutorial: http://www.asp.net/mvc/overview/getting-started/introduction/creating-a-connection-string

I create model and context(MovieDBContext) class and try to setup connection:

<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-MvcMovie-20130603030321.mdf;Initial Catalog=aspnet-MvcMovie-20130603030321;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="MovieDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True" providerName="System.Data.SqlClient"
/>


When i try to access to page where i show all movies :

public ActionResult Index()
{
return View(db.Movies.ToList());
}


I get this exception:
enter image description here

I try to edit connection strings like this and also not working:

<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-MvcMovie-20130603030321.mdf;Initial Catalog=aspnet-MvcMovie-20130603030321;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="MovieDBContext" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True" providerName="System.Data.SqlClient"
/> </connectionStrings>


I get this excpetion when i use
(local)MSSQLLocalDB


enter image description here

What i do wrong ?

Answer

The initial Catalog is missing in MovieDBContext connection string. It needs to be as follows:

 <add name="MovieDBContext"   connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Movies.mdf;Initial Catalog=Movies;Integrated Security=True" providerName="System.Data.SqlClient"/> 
Comments