如何解决数据库初始化错误?

时间:2014-03-13 04:37:13

标签: c# sql-server linq entity-framework

我一直在测试不同的东西,并得出结论,以下错误是我的数据库不会初始化并抛出异常的原因。当我引用数据库并初始化它时会发生异常。你可以看到我的Web.config连接字符串很好。我正在使用Entity Framework 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
}

3 个答案:

答案 0 :(得分:0)

您应该在连接字符串

中提及useridpassword
<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"/>

答案 1 :(得分:0)

您的连接字符串不是EF所要求的格式,实际上应该与此类似:

<add name="XYZ" connectionString="metadata=res://*/ModEntity.csdl|res://*/ModEntity.ssdl|res://*/ModEntity.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />

答案 2 :(得分:0)

也可以使用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=&quot;data source=servername;initial catalog=databasename;user id=username;password=password;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

将ModelName替换为您的Model并更改数据库上的连接。