Reset Identity column to zero in SQL Server?

前端 未结 6 2322
不知归路
不知归路 2021-02-19 04:36

How can I reset the Identity column of a table to zero in SQL Server?

Edit:

How can we do it with LINQ to SQL ?

6条回答
  •  南方客
    南方客 (楼主)
    2021-02-19 04:49

    Generic extension method:

        /// 
        /// Reseeds a table's identity auto increment to a specified value
        /// 
        /// The row type
        /// The type of the identity column
        /// The table to reseed
        /// The new seed value
        public static void ReseedIdentity(this Table table, TIdentity seed)
            where TEntity : class
        {
            var rowType = table.GetType().GetGenericArguments()[0];
    
            var sqlCommand = string.Format(
                "dbcc checkident ('{0}', reseed, {1})",
                table.Context.Mapping.GetTable(rowType).TableName, 
                seed);
    
            table.Context.ExecuteCommand(sqlCommand);
        }
    

    Usage: myContext.myTable.ReseedIdentity(0);

提交回复
热议问题