EF Core 6 - Truncate Table

Cenk 1,036 Reputation points
2023-01-25T06:54:42.34+00:00

Hi,

How can I use the truncate table in EF Core 6? I tried this but didn't delete rows.

_oyunPalasContext.RazerReconciliation.FromSqlRaw("TRUNCATE TABLE RazerReconciliation");
Developer technologies | .NET | Entity Framework Core
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2023-01-25T09:34:50.47+00:00

    @Cenk, Welcome to Microsoft Q&A, based on my test, I reproduced your problem.

    As usual, FromSqlRaw method is used to query the data from the database.

    If you want to execute some sqlcommand in ef core, you could try to use ExecuteSqlRaw method.

    Here is a code example you could refer to.

    MyContext context=new MyContext();
    context.Database.ExecuteSqlRaw("TRUNCATE TABLE stus");
    

    Based on my test, the above code could clear all the data of table stus.

    Hope my code could help you.

    Best Regards,

    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2023-01-25T11:22:57.64+00:00

    Although Database.ExecuteSqlRaw works I would use a method such as the following which validates the table was actually truncated and if there is an exception you can log it.

    public static (bool success, Exception exception) TruncateTable(string? connectionString, string tableName)
    {
        var truncateStatement = $"TRUNCATE TABLE {tableName};";
        using var cn = new SqlConnection(connectionString);
        using var cmd = new SqlCommand(truncateStatement, cn);
        cn.Open();
        try
        {
            cmd.ExecuteNonQuery();
            cmd.CommandText = $"SELECT COUNT(*) FROM dbo.{tableName}";
            return (Convert.ToInt32(cmd.ExecuteScalar()) == 0, null)!;
        }
        catch (Exception ex)
        {
    
            return (false, ex);
        }
    }
    

    So in this example there is a table Post to truncate

    using var context = new Context();
    var (success, exception) = TruncateTable(context.Database.GetConnectionString(), nameof(Post));
    if (success)
    {
        // done
    }
    else
    {
        // inspect exception
    }
    
    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.