Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 213
Ivan Avatar asked Aug 04 '16 12:08

Ivan


People also ask

What is the connection string for LocalDB?

Start LocalDB and connect to LocalDB To connect to a specific database by using the file name, connect using a connection string similar to Server=(LocalDB)\MSSQLLocalDB;Integrated Security=true;AttachDbFileName=D:\Data\MyDB1. mdf .

How can I set an SQL Server connection string?

You can either use the new operator to make that directly. For example: SqlConnection conn = new SqlConnection( new SqlConnectionStringBuilder () { DataSource = "ServerName", InitialCatalog = "DatabaseName", UserID = "UserName", Password = "UserPassword" }. ConnectionString );


1 Answers

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"/> 
like image 110
Vinod Ghunake Avatar answered Sep 20 '22 17:09

Vinod Ghunake