背景
我正在处理一个包含遗留代码和实体框架代码的项目。我被建议使用特定的数据服务方法来处理来自数据库的记录。记录是通过实体框架检索的,我将PK传递到dataservice函数中执行操作。使用实体框架和SqlConnection?
前提对成功和失败
如果网络是高达,既DB调用(实体SQL)会成功。 如果网络出现故障,然后回来并执行此代码,那么它将检索带有实体框架的锁定记录,但随后失败,并显示下面的SqlException
。
这让我想到,这里发生了什么,可能导致SqlConnection
失败,尽管EF能够建立连接。
代码示例
一个代码示例如下:
public void HandleNetworkBecomesAvailable() {
_entityFrameworkDataService.ReleaseRecords();
}
EntityFrameworkDataService.cs
public void ReleaseRecords()
{
using (var context = new Entities()) // using EntityConnection
{
var records = context.Records.Where(
record => record.IsLocked).ToList();
foreach (var record in records)
{
_sqlConnectionDataService.UnlockRecord(record.ID);
}
}
}
SqlConnectionDataService.cs
public void UnlockRecord(int recordId)
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Sqlconnection"].ConnectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = @"UPDATE [Records] SET [IsLocked] = 0";
//etc
command.ExecuteNonQuery();
}
}
}
的App.config
<add name="EntityConnection" connectionString="metadata=res://*/FooDatabase.csdl|res://*/FooDatabase.ssdl|res://*/FooDatabase.msl;provider=System.Data.SqlClient;provider connection string="data source=RemoteServer;initial catalog=FooDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="SqlConnection" connectionString="Server=RemoteServer;Database=FooDatabase;Trusted_Connection=True" />
现在,在与我的同事讨论后,我最终将逻辑转移到实体框架dataservice中,并在那里进行工作。但是我仍然不确定为什么连接失败。
编辑:实际的错误是:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Inner Exception:
The network path was not found
但实体框架是使用相同的网络路径,可以在App.config两个连接字符串中可以看出。
什么是异常的实际消息文本?有没有内在的例外? – 2014-09-23 16:04:33
看来服务器无法联系到,您确定使用的连接字符串是否正常? – pollirrata 2014-09-23 16:12:01
这个异常基本上说它不能使用你提供的连接字符串连接到sql server。如果你断断续续地发现它代表网络问题,而不是代码中的任何东西。如果你一致地得到它,那么你使用的连接字符串是错误的。 – 2014-09-23 16:13:14