Entity Framework 4.1 Code First 中的命令超时

31

我该如何设置DbContext的命令超时时间?

5个回答

74

MikeWyatt的回答很有帮助,但是当你在已经使用Entity Framework的项目中应用这个“hack”时,可能会遇到问题,并且在这些项目中你会使用指定了DefaultContainerName属性的EntityDataSource。 - user1296528
如果你使用任何初始器(Database.SetInitializer(...), 请小心。初始器将被 this.ObjectContext getter 调用。 - Alexander Bartosh
@AlexanderBartosh:您能详细说明可能的问题吗?我使用Database.SetInitializer()。我应该注意什么? - hofnarwillie

7

对于Entity Framework的后续版本,更好的解决方案是使用DbContext.Database.CommandTimeout属性。我认为这是在EF 6中引入的。


0
请在执行任何数据库命令之前尝试以下代码。以下代码需要3/4分钟才能执行完毕。因此,在执行命令之前,CommandTimeout设置为300(以秒为单位)。
public List<CollectionEfficiencyByUnitOfficeSummary> ReadCollectionEfficiencyByUnitOfficeSummary(string yearMonth, string locationCode, string reportType)
        {
            ((System.Data.Entity.Infrastructure.IObjectContextAdapter)context).ObjectContext.CommandTimeout = 300;
            return context.CollectionEfficiencyByUnitOfficeSummary(yearMonth, locationCode, reportType).ToList();
        }

0

我在使用EntityFramework v4.4和CodeFirstStoredProc v2.2时遇到了同样的问题。由于升级不是我的选择,所以我必须更新CodeFirstStoredProcs.cs文件,将一个新的可空int参数命名为“commandTimeout”传递给以下3个方法。

public static ResultsList CallStoredProc<T>(this DbContext context, StoredProc<T> procedure, T data, int? commandTimeout = null)
    {
        IEnumerable<SqlParameter> parms = procedure.Parameters(data);
        ResultsList results = context.ReadFromStoredProc(procedure.fullname, parms, commandTimeout, procedure.returntypes);
        procedure.ProcessOutputParms(parms, data);
        return results ?? new ResultsList();
    }

public static ResultsList CallStoredProc(this DbContext context, StoredProc procedure, IEnumerable<SqlParameter> parms = null, int? commandTimeout = null)
    {
        ResultsList results = context.ReadFromStoredProc(procedure.fullname, parms, commandTimeout, procedure.returntypes);
        return results ?? new ResultsList();
    }

在下面的方法中,这里是检查参数并应用 cmd.connectionTimeout 值的条件。
internal static ResultsList ReadFromStoredProc(this DbContext context,
        String procname,
        IEnumerable<SqlParameter> parms = null,
        int? commandTimeout = null,
        params Type[] outputtypes)
    {
        // create our output set object
        ResultsList results = new ResultsList();

        // ensure that we have a type list, even if it's empty
        IEnumerator currenttype = (null == outputtypes) ?
            new Type[0].GetEnumerator() :
            outputtypes.GetEnumerator();

        // handle to the database connection object
        var connection = (SqlConnection)context.Database.Connection;
        try
        {
            // open the connect for use and create a command object
            connection.Open();
            using (var cmd = connection.CreateCommand())
            {
                // command to execute is our stored procedure
                cmd.CommandText = procname;
                cmd.CommandType = System.Data.CommandType.StoredProcedure;

                if (commandTimeout.HasValue)
                {
                    cmd.CommandTimeout = commandTimeout.Value;
                }

                // move parameters to command object
                if (null != parms)
                    foreach (SqlParameter p in parms)
                        cmd.Parameters.Add(p);
                //    foreach (ParameterHolder p in parms)
                //        cmd.Parameters.Add(p.toParameter(cmd));

                // Do It! This actually makes the database call
                var reader = cmd.ExecuteReader();

                // get the type we're expecting for the first result. If no types specified,
                // ignore all results
                if (currenttype.MoveNext())
                {
                    // process results - repeat this loop for each result set returned by the stored proc
                    // for which we have a result type specified
                    do
                    {
                        // get properties to save for the current destination type
                        PropertyInfo[] props = ((Type)currenttype.Current).GetMappedProperties();

                        // create a destination for our results
                        List<object> current = new List<object>();

                        // process the result set
                        while (reader.Read())
                        {
                            // create an object to hold this result
                            object item = ((Type)currenttype.Current).GetConstructor(System.Type.EmptyTypes).Invoke(new object[0]);

                            // copy data elements by parameter name from result to destination object
                            reader.ReadRecord(item, props);

                            // add newly populated item to our output list
                            current.Add(item);
                        }

                        // add this result set to our return list
                        results.Add(current);
                    }
                    while (reader.NextResult() && currenttype.MoveNext());
                }
                // close up the reader, we're done saving results
                reader.Close();
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Error reading from stored proc " + procname + ": " + ex.Message, ex);
        }
        finally
        {
            connection.Close();
        }

        return results;
    }
}

希望这能帮到你,因为我曾经四处寻找帮助,但什么都没有找到,直到我意识到我可以不更新CodeFirstStoredProcs的版本,这样就不用强制更新EntityFramework了。


-8
如果您正在使用SqlServer,只需将以下内容添加到连接字符串中: "... Connect Timeout = x" 其中x是以毫秒为单位的超时时间。

10
连接超时是用于打开新连接的超时时间,而不是执行命令的超时时间。 - MikeWyatt

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