如何为Entity框架中实体类型上下文设置命令超时?
Hey there! Since you're working with a DBEntities context (which is a modern DbContext implementation, not the legacy ObjectContext), setting a command timeout is straightforward. Here are a few approaches tailored to your repository setup:
1. Set Timeout Directly in Your ShopRepository Constructor
You can set the timeout right when initializing your repository, so every query using this instance will inherit the setting. Just access the Database.CommandTimeout property on your _contextObject:
public class ShopRepository : GenericRepository<tbl_Shop> { private DBEntities _contextObject; public ShopRepository(DBEntities context) : base(context) { this._contextObject = context; // Set timeout in seconds (e.g., 300 seconds = 5 minutes) _contextObject.Database.CommandTimeout = 300; } // Optional: Add a method to dynamically adjust the timeout later public void UpdateCommandTimeout(int seconds) { _contextObject.Database.CommandTimeout = seconds; } }
2. Global Timeout for All DBEntities Instances
If you want every usage of DBEntities (across all repositories) to use the same timeout, set it directly in the DBEntities class constructor:
public class DBEntities : DbContext { public DBEntities() : base("YourConnectionStringName") { // This applies to all queries using this context this.Database.CommandTimeout = 300; } }
3. Per-Query Timeout for Specific Operations
Sometimes you only need a longer timeout for a single slow query. You can override the default timeout directly on the query itself:
// Example: A slow LINQ query with a custom timeout var slowShopQuery = await _contextObject.tbl_Shop .Where(s => s.SomeComplexCondition) .ToListAsync(); // For raw SQL queries: var rawSqlShops = _contextObject.tbl_Shop .SqlQuery("SELECT * FROM tbl_Shop WHERE SomeHeavyFilter") .CommandTimeout(300) .ToList();
Quick Notes:
- The
CommandTimeoutvalue is in seconds. Setting it tonullwill use the default timeout from your database connection string or the ADO.NET driver (usually 30 seconds). - If your
GenericRepositorybase class handles context operations, you could also add a timeout-setting method there to reuse across all your repositories.
内容的提问来源于stack exchange,提问作者Keren Caelen

