创建连接字符串并使用SQL Server LocalDB

时间:2016-08-04 12:24:04

标签: c# asp.net sql-server asp.net-mvc localdb

当我尝试从visual studio 15连接到localdb时遇到问题。 我已经安装了SQL Server Express 2016

我在本教程中提到:http://www.asp.net/mvc/overview/getting-started/introduction/creating-a-connection-string

我创建模型和上下文(MovieDBContext)类并尝试设置连接:

<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"
/>

当我尝试访问我显示所有电影的页面时:

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

我得到这个例外: enter image description here

我尝试编辑这样的连接字符串,但也无法正常工作:

  <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>

当我使用(local)MSSQLLocalDB

时,我得到了这个问题

enter image description here

我做错了什么?

1 个答案:

答案 0 :(得分:12)

MovieDBContext连接字符串中缺少初始目录。 它需要如下:

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