Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I decrease the connect timeout with Entity Framework?

I want to make a database connection to my SQL Server fail fast. How can I decrease the timeout? I've tried adding Connection Timeout=1 in my connection string, however this doesn't seem to make a difference.

With Connection Timeout=500, it takes about 8 min 30 seconds to timeout. This is expected. With Connection Timeout=1, it takes around 40 seconds to timeout which is way longer than expected.

I found the EntityConnection.ConnectionTimeout property but it is read only. Is there anything else I can do to decrease this timeout? Is this an issue with Entity?

UPDATE: Here is my connect string. It still takes ~40 seconds to timeout.

<add name="KofaxAdminToolsEntities" connectionString="metadata=res://*/DB.Model.KofaxAdminTools.csdl|res://*/DB.Model.KofaxAdminTools.ssdl|res://*/DB.Model.KofaxAdminTools.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MY_DATASOURCE;initial catalog=MY_CATALOG;persist security info=True;user id=MY_USER;password=MY_PASSWORD;MultipleActiveResultSets=True;App=EntityFramework;Connection Timeout=1&quot;" providerName="System.Data.EntityClient" />

UPDATE 2: So I discovered that the timeout was a tcp timeout, not a sql connect timeout. If my machine were able to reach the host, @marc_s solution would have worked, however, since I cannot reach that host, the tcp timeout comes into play. Does anyone know how to decrease the tcp timeout for a SqlConnection?

like image 566
Blaine Avatar asked Nov 12 '22 11:11

Blaine


1 Answers

Where and how did you specify that connection timeout?

I just tried and added this to my EF connection string (using EF database-first) - and it works as expected: with SQL Server service stopped, the connection attempts time out almost immediately....

<add name="myEntities" 
     connectionString="metadata=res://*/People.csdl|res://*/People.ssdl|res://*/People.msl;provider=System.Data.SqlClient;
             provider connection string=&quot;data source=.;initial catalog=mydb;
             integrated security=True;connect timeout=1;multipleactiveresultsets=True;
                                      ***************** 
             App=EntityFramework&quot;" 
     providerName="System.Data.EntityClient" />

(EF connection string broken up and wrapped for clarity - this will be just one long line in your web.config)

You need to add connect timeout=x (where x is in seconds, any value bigger than 0 is ok) inside the provider connection string= value of your EF connection string.

like image 169
marc_s Avatar answered Nov 15 '22 05:11

marc_s