简体   繁体   中英

Entity Framework Query Timeout

In my controller I have the following code:

    public ActionResult Syslogs(string IPAddress) {
        IEnumerable<Syslogd> syslogs = db.Syslogds.Take(100).ToList();

        if (!String.IsNullOrEmpty(IPAddress)) {
            syslogs = db.Syslogds.Where(s => s.MsgHostname == IPAddress).Take(100).ToList();
        }

        return View(syslogs.ToList());
    }

The query times out whenever I pass a certain value to the IPAddress variable. I'm not sure why that is happening or how I can prevent it. Does the value not exist in the database or is it just taking a long time to find it? Here is the error message I receive:

An exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: An error occurred while executing the command definition. See the inner exception for details.

The inner exception:

{"Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."}

It's possible that the value doesn't exist, but a Timeout just means that the query didn't complete in the time given for the command to execute. I think the default timeout for EF is 30 seconds for commands.

Basic question, but, if your Syslogd table has many records, is there an index on MsgHostname?

As Ryan said default timeout for EF is 30 seconds for commands . So you can increase the execution timeout time.

By using CommandTimeOut :

// Specify a timeout for queries in this context, in seconds.
context.CommandTimeout = 120;  

Reference

Consider this also:

  1. Moreover you are using .ToList() which is force query execution by immediate and i think you can avoid that to improve the performance.
  2. IEnumerable is suitable for querying data from in-memory collections like List, Array etc.But not suitable for querying data from out-memory (like remote database, service) collections and paging.

So i strongly recommend to use IQueryable in this case.

Reference
codeproject

IQueryable Vs. IEnumerable in terms of LINQ to SQL queries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM