如何解决数据库初始化错误
本文关键字:数据库 初始化 错误 解决 何解决 | 更新日期: 2023-09-27 17:50:01
我一直在测试不同的东西,并得出结论,以下错误是我的数据库无法初始化并抛出异常的原因。当我引用数据库并初始化它时发生异常。我的网络。如您所见,配置连接字符串很好。我正在使用实体框架6,MSSQL和c#。如有任何帮助,不胜感激。
异常:Cannot open database '"xxx'" requested by the login. The login failed.'r'nLogin failed for user 'xxxx'.
连接字符串:
<add name="WebDBContext" connectionString="Data Source=(LocalDb)'v11.0;Initial Catalog=WebDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
代码:private SchoolContext db = new SchoolContext();
public ViewMethod Method()
{
var students = from s in db.Students select s; //EXCEPTION IS THROWN HERE
}
您应该在连接字符串
中提及userid
和password
<add name="WebDBContext" connectionString="Data Source=(LocalDb)'v11.0;Initial Catalog=WebDB;Integrated Security=SSPI;User ID=xyz;pwd=top$secret;" providerName="System.Data.SqlClient"/>
您的连接字符串不是EF所要求的格式,它实际上应该看起来像这样:
<add name="XYZ" connectionString="metadata=res://*/ModEntity.csdl|res://*/ModEntity.ssdl|res://*/ModEntity.msl;provider=System.Data.SqlClient;provider connection string="Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
也可以使用linq查询
var students = db.Students;
<connectionStrings>
<add name="WebDBContext" connectionString="metadata=res://*/Models.ModelName.csdl|res://*/Models.ModelName.ssdl|res://*/Models.ModelName.msl;provider=System.Data.SqlClient;provider connection string="data source=servername;initial catalog=databasename;user id=username;password=password;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
将ModelName替换为Model并更改数据库上的连接