数据库
首页 > 数据库> > c# – 创建连接字符串并使用SQL Server LocalDB

c# – 创建连接字符串并使用SQL Server 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>

当我使用(本地)MSSQLLocalDB时,我得到了这个激动

enter image description here

我做错了什么?

解决方法:

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

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

标签:c,sql-server,asp-net,asp-net-mvc,localdb
来源: https://codeday.me/bug/20190716/1475119.html