我有个小问题。我的应用程序在本地主机上运行并且一切正常,但是当我将其上传到生产 Web 服务器并且我想连接数据库时,我只收到“抱歉,处理您的请求时发生错误。”。当我尝试没有数据库交互的页面时,它起作用了。我正在使用 Entity Framework,但我不确定我的连接字符串是否正确。
这是本地主机的连接字符串:
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=localhost\MSSQL;Integrated Security=SSPI;Initial Catalog=KravmagaIS" />
<add name="KravmagaISEntities" connectionString="metadata=res://*/Models.KravmagaModel.csdl|res://*/Models.KravmagaModel.ssdl|res://*/Models.KravmagaModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=ISKUDA-NTB\MSSQL;Initial Catalog=KravmagaIS;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
这个用于生产服务器:
<connectionStrings>
<add name="ApplicationServices" connectionString="Data Source=192.168.1.5;User ID=db3542;Password=****;Initial Catalog=db3542" />
<add name="KravmagaISEntities" connectionString="metadata=res://*/Models.KravmagaModel.csdl|res://*/Models.KravmagaModel.ssdl|res://*/Models.KravmagaModel.msl;provider=System.Data.SqlClient;provider connection string='Data Source=192.168.1.5;User ID=db3542;Password=*****;Initial Catalog=db3542'" providerName="System.Data.EntityClient" />
</connectionStrings>
有没有错误?我确定密码是正确的。
感谢您的帮助。
编辑:
对不起我的错误。 :-/连接正常。但是生产服务器中的关系是问题的原因。
我有类(class) Training
和类(class) Instructor
。 (培训只有一名讲师)。
当我在 View 中调用时:
@training.InstructorID
我通常会得到培训讲师的 ID,但是当我打电话时:
@training.Instructor.Fullname
我收到错误消息。在本地主机上一切正常。
有什么想法吗?谢谢。
最佳答案
我想相同的代码在您的开发环境中运行,所以这应该不是您的代码的问题。另外,因为您提到加载了 Training
,所以连接到数据库服务器应该不是问题。
看起来延迟加载不起作用,这又回到了我之前的说明,即生产连接字符串中未启用 MARS (MultipleActiveResultSets)。 MARS 允许您在循环中读取一个查询的结果,同时执行另一个查询以获取详细信息。典型的例子是:
// Executes something kile SELECT * FROM Trainings and has opened
// DataReated for the whole duration of the loop.
foreach(var training in context.Trainings)
{
// Executes something like SELECT * FROM Instructors WHERE Id = @Id
// and opens its own DataReader to get the result.
// If MARS is not enabled or not supported you will get an exception
var fullName = training.Instructor.FullName;
}
顺便说一句。该代码是 N+1 问题的示例,因为它将执行 1 个外部查询,并且对于外部查询的每个结果,它将执行 1 个内部查询。因此,对于来自外部查询的 N 个结果,您将执行 N 个子查询 => 这很糟糕 并且应该通过使用另一种加载技术尽可能避免。例如:
// Loads both trainings ana related instructors in the same query.
foreach(var training in context.Trainings.Include("Instructor"))
{
// No query is executed here because instructor is already loaded.
var fullName = training.Instructor.FullName;
}
关于entity-framework - Entity Framework 部署 - 连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5702966/