简体   繁体   中英

How can I avoid TimeOut exception using Entity Framework with a stored procedure?

I'm using Entity Framework to call a stored procedure which takes 2 minutes to execute. As a result, I get a timeout exception.

Is there any way I can use my stored procedure without getting a timeout exception?

Entity Framework uses underlying connection provider and depends on the timeout provided by the provider. Usually its 30 seconds for the timeout if I am not mistaken.

However you can always increase the timeout by setting value of context.CommandTimeout = 120 in seconds

Hope this helps.

You can control Timeout value using connection string also.

<connectionStrings>

<add name="AdventureWorksEntities"
connectionString="metadata=.\AdventureWorks.csdl|.\AdventureWorks.ssdl|.\AdventureWorks.msl;
provider=System.Data.SqlClient;provider connection string='Data Source=localhost;
Initial Catalog=AdventureWorks;Integrated Security=True;Connection Timeout=60;
multipleactiveresultsets=true'" providerName="System.Data.EntityClient" />

</connectionStrings>

Also you can set it for your DBContext.

public class MyDatabase : DbContext
{
    public MyDatabase ()
        : base(ContextHelper.CreateConnection("Connection string"), true)
    {
        ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
    }
}

For EF CORE, .NET 6 If you wanted, just set it on the database context under the using statement. If you don't want to set it across the entire application.

            await using var ctx = new MYDbContext(dbOptions);
            ctx.Database.SetCommandTimeout(120);
            var result = ctx.Database.ExecuteSqlRaw("exec [dbo].[MYSP]");

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