Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command Timeout with Entity Framework 4.1 Code First

How can I set the command timeout of a DbContext?

like image 266
MikeWyatt Avatar asked Jun 21 '11 17:06

MikeWyatt


People also ask

How to set sql command timeout in entity framework?

You can use DbContext. Database. CommandTimeout = 180; It's pretty simple and no cast required.

How do I set the execution timeout in Entity Framework?

Set database timeout in Entity Framework Try this on your context:...public class MyDatabase : DbContext { public MyDatabase () : base(ContextHelper. CreateConnection("Connection string"), true) { ((IObjectContextAdapter)this). ObjectContext. CommandTimeout = 180; } } ...

How to set timeout in DbContext?

public partial class MyEntities : DbContext { public MyEntities() : base("name=MyConnectionStringName") { } ... } In your code, instantiate the Container class and if you need to use a custom timeout for a specific command, set it manually using the provided methods. using (var db = new MyEntitiesContainer()) { db.


2 Answers

I found this solution after another Google search. You can access the ObjectContext for a DbContext by casting this to an IObjectContextAdapter.

From http://social.msdn.microsoft.com/Forums/en-ZA/adodotnetentityframework/thread/6fe91a64-0208-4ab8-8667-d061af340994:

public class MyContext : DbContext {     public MyContext ()         : base(ContextHelper.CreateConnection("my connection string"), true)     {         ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 300;     } } 
like image 152
MikeWyatt Avatar answered Sep 24 '22 23:09

MikeWyatt


A better solution to this for later versions of Entity Framework is to use the DbContext.Database.CommandTimeout property. I think this came in with EF 6.

like image 44
Josh Gallagher Avatar answered Sep 23 '22 23:09

Josh Gallagher