使用EntityFramework时设置连接超时时间

9

我希望将ConnectionTimeout设置为默认值15秒以外的其他值。我继承了一些使用EntityFramework的代码,app.config看起来像这样:

<configuration>
   <configSections>
      <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxxx" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS; Integrated Security=True; ConnectionTimeout=30; MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
  <parameters>
    <parameter value="Data Source=.\SQLEXPRESS; Integrated Security=True; ConnectionTimeout=30; MultipleActiveResultSets=True" />
  </parameters>
</defaultConnectionFactory>
</entityFramework>

我是那个为了使事情正常运作而添加了该部分的人。我可以通过在以下位置设置断点来确定它是否有效:

var adapter = (IObjectContextAdapter) this;
var objectContext = adapter.ObjectContext;
objectContext.CommandTimeout = CommandTimeoutSeconds;
int test = objectContext.Connection.ConnectionTimeout;

测试始终为15,是怎么回事?可以有人告诉我如何设置ConnectionTimeout吗?我尝试过“ConnectionTimeout”和“Connection Timeout”,即没有空格与有空格。

有人能帮帮我吗?我快抓狂了。我相信这只是一个简单的修复! Dave

附加信息。回应评论,这是我的DbContext派生类...

public class SessionDataContext : DbContext
{
    // Command timeout (seconds)
    private const int CommandTimeoutSeconds = 30;

    /// <summary>
    /// Constructor that takes db name.
    /// The connection string and db itself is configured in the this project's app.config file
    /// </summary>
    /// <param name="dbName"></param>
    public SessionDataContext(string dbName) : base(dbName)
    {
        Database.SetInitializer(new SessionDataContextInitializer());

        // Set timeout (based on code from https://dev59.com/p2025IYBdhLWcg3wEhnr)
        var adapter = (IObjectContextAdapter) this;
        var objectContext = adapter.ObjectContext;
        objectContext.CommandTimeout = CommandTimeoutSeconds;
        int test = objectContext.Connection.ConnectionTimeout;
    }

    /// <summary>
    /// Session table's records
    /// </summary>
    public DbSet<Session> Sessions { get; set; }

    /// <summary>
    /// SessionType table's records
    /// </summary>
    public DbSet<SessionType> SessionTypes { get; set; }
}

你如何创建派生自DbContext的类?你是否在那里传递连接字符串名称? - Pawel
嗨,Pawel,我在问题中放置了DbContext驱动类。感谢您查看我的问题。 - Dave
你看过这个网址吗:https://dev59.com/p2025IYBdhLWcg3wEhnr? - Alex Paven
1个回答

7
这是我的错误导致了问题!我把答案放在这里,以便将来有人遇到同样的问题。我之前写的所有内容都是正确的并且可以正常工作。然而,我查看的app.config文件位于一个类库中(我们的DataAccess层)。事实上,它根本没有被使用,而是使用默认的EntityFramework设置。我不确定是什么让我尝试移动app.config设置,但我把DataAccess层的app.config设置移到主app.config中后,一切都运行得非常好。除了我继承了这段代码之外,我的辩解只能是不清楚app.config中的值是否被使用,并且不需要在自己的代码中调用或使用它们。相反,MultipleActiveResultSets和ConnectionTimeout由底层的Entity Framework使用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接