How to set CommandTimeout for DbContext?

浪子不回头ぞ 提交于 2019-11-27 00:33:08

问题


I am looking a way to set CommandTimeout for DbContext. After searching I found the way by casting DbContext into ObjectContext and setting value for CommandTimeout property of objectContext.

var objectContext = (this.DbContext as IObjectContextAdapter).ObjectContext;

But I have to work with DbContext.


回答1:


It will work with your method.

Or subclass it (from msdn forum)

public class YourContext : DbContext
{
  public YourContext()
    : base("YourConnectionString")
  {
    // Get the ObjectContext related to this DbContext
    var objectContext = (this as IObjectContextAdapter).ObjectContext;

    // Sets the command timeout for all the commands
    objectContext.CommandTimeout = 120;
  }
}



回答2:


var ctx = new DbContext();
ctx.Database.CommandTimeout = 120;



回答3:


This may help you.

public class MyContext : DbContext
{    
    public MyContext () : base(ContextHelper.CreateConnection("my connection string"), true)
    {
        ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 300;
    }
}



回答4:


I find that changing the .tt file works for me as I don't lose the change later on:

Add this line:

((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 300;

Right after the DbContext creator and before the !loader.IsLazy construct:

<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext
{
    public <#=code.Escape(container)#>()
        : base("name=<#=container.Name#>")
    {
        ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 300;
<#
if (!loader.IsLazyLoadingEnabled(container))

It should then appear in your generated Context.cs:

public MyEntities()
            : base("name=MyEntities")
        {
            ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 300;
        }



回答5:


Here's how I solved this problem when using an EDMX file. This solution changes the default T4 template to make the generated class inherit from a custom DbContext class, which specifies a default command timeout, and a property to change it.

I'm using Visual Studio 2012 and EF 5.0. Your experience may differ with other versions.

Create a custom DbContext class

public class CustomDbContext : DbContext
{
    ObjectContext _objectContext;

    public CustomDbContext( string nameOrConnectionString )
        : base( nameOrConnectionString )
    {
        var adapter = (( IObjectContextAdapter) this);

        _objectContext = adapter.ObjectContext;

        if ( _objectContext == null )
        {
            throw new Exception( "ObjectContext is null." );    
        }

        _objectContext.CommandTimeout = Settings.Default.DefaultCommandTimeoutSeconds;
    }

    public int? CommandTimeout
    {
        get
        {
            return _objectContext.CommandTimeout;
        }
        set
        {
            _objectContext.CommandTimeout = value;
        }
    }
}

This has an optional feature: I'm not hard-coding the default command timeout. Instead, I'm loading it from the project settings so that I can change the value in a config file. How to setup and use project settings is not in the scope of this answer.

I'm also not hard-coding the connection string or connection string name. It's already passed into the constructor by the generated context class, so it makes no sense to hard-code it here. This is nothing new; the EDMX file already generates the following constructor for you, so we are just passing along the value.

public MyEntities()
    : base("name=MyEntities")
{
}

(This instructs EF to load the connection string named "MyEntities" from the config file.)

I'm throwing a custom exception if the ObjectContext is ever null. I don't think it ever will be, but it's more meaningful than getting a NullReferenceException.

I store the ObjectContext in a field so that I can make a property to access it to override the default.

Modifying the entity context T4 template

In the Solution Explorer, expand the EDMX file so that you see the T4 templates. They have a .tt extension.

Double click the "MyModel.Context.tt" file to open it. Around line 57 you should see this:

<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext

This template line generates the class definition of your "MyEntities" class, which inherits DbContext.

Change the line so that the generated class inherits CustomDbContext, instead:

<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : CustomDbContext

As soon as you save this file it should regenerate the class. If not, you can right-click the EDMX file and select "Run Custom Tool". If you expand the "MyModel.Context.tt" file under your EDMX file, you will see "MyModel.Context.cs". That's the generated file. Open it, and you should see that it now inherits CustomDbContext.

public partial class MyEntities : CustomDbContext

That's all there is to it.

Issues

Once you change the context class from DbContext to CustomDbContext, Visual Studio will give you an error if you try to add a new MVC controller class using the "Controller with read/write actions and views, using Entity Framework" template. It will say "Unsupported context type.". To get around this, open the generated "MyModel.Context.cs" class, and temporarily change the type it inherits back to DbContext. After adding your new controller, you can change it back to CustomDbContext.




回答6:


I like the extension approach:

public static class DbContextExtensions
{
   public static void SetCommandTimeout(this ObjectContext dbContext,
       int TimeOut)
   {
       dbContext.CommandTimeout = TimeOut;
   }
}

and then simply

((IObjectContextAdapter)cx).ObjectContext.SetCommandTimeout(300);



回答7:


If it can help, this is the VB.Net solution:

Dim objectContext As Objects.ObjectContext = CType(Me,IObjectContextAdapter).ObjectContext
objectContext.commandTimeout = connectionTimeout



回答8:


I came here looking for an example of setting the timeout for a single command rather than such a global setting.

I figure that it will probably help someone to have an example of how I achieved this:

var sqlCmd = new SqlCommand(sql, context.Database.Connection as SqlConnection);
sqlCmd.Parameters.Add(idParam);
sqlCmd.CommandTimeout = 90;

if (sqlCmd.Connection.State == System.Data.ConnectionState.Closed)
{
    sqlCmd.Connection.Open();
}
sqlCmd.ExecuteNonQuery();
sqlCmd.Connection.Close();


来源:https://stackoverflow.com/questions/10549640/how-to-set-commandtimeout-for-dbcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!