'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?



Solution 1:[1]

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.

Solution 2:[2]

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;
    }
}

Solution 3:[3]

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]");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 marc_s
Solution 2 Vandita
Solution 3 Siemens