Background
I'm working on a project which contains both legacy code and Entity Framework code. I was advised to use a specific dataservice method to operate on a record from the database. The record was retrieved via Entity Framework, and I passed the PK into the dataservice function to perform the operation.
Preconditions for success and failure
If the network was up, both DB calls (entity and SQL) would succeed. If the network went down, then came back up and this code was executed, then it would retrieve the locked records with entity framework but then fail with the SqlException below.
This got me thinking, what is going on here that might cause the SqlConnection to fail despite EF being able to make the connection.
Code Samples
A code sample follows:
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" />
Now, after discussing with my coworkers, I ended up moving the logic into the entity framework dataservice and doing the work there. But I'm still not quite sure why the connection kept failing.
Edit: The actual error is:
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
But Entity Framework is using the same network path, as can be seen in the two connection strings in the App.config.