Semih Can Bilgen
Semih Can Bilgen

Reputation: 414

Reset ID column of database records

I have a problem which can not solve by myself. My customer request reset button which provide delete all records and reset ID.

There is not problem for delete records but i can not reach reset id.

private void SettingsDLT_delete_button_Click(object sender, EventArgs e)
{
    MainWeight main = new MainWeight();
    main.RemoveAllWeight();
}

And controller:

public void RemoveAllWeight()
{
    try
    {
        using (DaghanKantarEntities context = new DaghanKantarEntities())
        {
            context.tbl_MainWeight.RemoveRange(
                context.tbl_MainWeight.Where(c => c.fldId != null));
            context.SaveChanges();
        }
    }
    catch (Exception exp)
    {
        throw new Exception("Hata: Kayıt Silinemedi - " + exp.Message.ToString(), exp);
    }
}

Upvotes: 0

Views: 2755

Answers (3)

Curros
Curros

Reputation: 11

Be careful, don't do like me, double check that the account have DBO authorization in order to execute that kind of code

Upvotes: 1

Semih Can Bilgen
Semih Can Bilgen

Reputation: 414

Thank you all for helps. I have solved my problem and will share codes for example. Regards.

private void SettingsDLT_delete_button_Click(object sender, EventArgs e)
    {
        MainWeight main = new MainWeight();
        main.ResetId();

    }

And Controller side

        public void ResetId()
    {
         try
        {
            using (DaghanKantarEntities context = new DaghanKantarEntities())
            {
                context.Database.ExecuteSqlCommand("DELETE FROM dbo.tbl_MainWeight");
                context.Database.ExecuteSqlCommand("DBCC CHECKIDENT ('tbl_MainWeight', RESEED, 0)");
                context.SaveChanges();

            }
        }
        catch (Exception exp)
        {
            throw new Exception("Hata: Kayıt Resetlenemedi - " + exp.Message.ToString(), exp);
        }

    }

Upvotes: 0

Drew Knab
Drew Knab

Reputation: 54

If you're working with SQL Server Management Studio you can reseed the primary key. You could run the following as a raw query rather than through entity:

DBCC CHECKIDENT ('table_name', RESEED, 1)

You could also TRUNCATE table_name instead of deleting all records.

Upvotes: 3

Related Questions