2014-09-23 83 views
3

背景

我正在处理一个包含遗留代码和实体框架代码的项目。我被建议使用特定的数据服务方法来处理来自数据库的记录。记录是通过实体框架检索的,我将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=&quot;data source=RemoteServer;initial catalog=FooDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" 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两个连接字符串中可以看出。

+1

什么是异常的实际消息文本?有没有内在的例外? – 2014-09-23 16:04:33

+0

看来服务器无法联系到,您确定使用的连接字符串是否正常? – pollirrata 2014-09-23 16:12:01

+0

这个异常基本上说它不能使用你提供的连接字符串连接到sql server。如果你断断续续地发现它代表网络问题,而不是代码中的任何东西。如果你一致地得到它,那么你使用的连接字符串是错误的。 – 2014-09-23 16:13:14

回答

1

您是否可以从实体框架的新弹性中获益?在哪里它透明地重试?如果错误是间歇性的,你甚至不会知道它重试了,而ADO.net让你知道它一旦失败就会失败。只是检查...

+0

我倾向于相信这一点,因为我知道实体框架做了某种形式的自定义连接管理。你能提供任何可能提供证据表明这种情况正在发生的链接吗? – 2014-09-23 17:28:01

+0

我唯一担心的是只有在实体框架查询成功时才会发生sql查询,这意味着连接必须可用。 – 2014-09-23 18:05:40

+0

您为多个活动结果集设置了什么值? – reckface 2014-09-23 18:17:57