我需要重置我的表的ID(身份),因为每次我进行更新时,我都必须在1上开始我的ID,因为它们每次都会将其增加到超过60,000条记录。我怎么能这样做?
using (DailyContext context= DailyContext.Create())
{
//cleaning old prices
foreach (var price in context.Prices)
{
context.DeleteObject(price);
}
context.SaveChanges();
for (int i = 0; i < newElements.Total; i++)
{
var newPrice = new Price()
{
Date = newElements.From.AddDays(i),
PriceFrom = newElements.Price,
TotalNights = newElements.TotalNights,
Profit = newElements.Profit
};
context.AddToPrices(newPrice);
}
context.SaveChanges();
}
答案 0 :(得分:1)
不要在EF中单独循环并删除价格,而只需使用ExecuteSqlCommand
到TRUNCATE
表格。
这两者都会清空它(比DELETE
更有效率)并重置IDENTITY
列值。
答案 1 :(得分:0)
要重置您需要在EF之外执行此操作的身份,您必须执行原始查询。您需要运行的查询是DBCC CHECKIDENT
,其中包含RESEED
参数。
using (DailyContext context= DailyContext.Create())
{
//cleaning old prices
foreach (var price in context.Prices)
{
context.DeleteObject(price);
}
context.SaveChanges();
//Reseed the identity to 0.
context.Database.ExecuteSqlCommand("DBCC CHECKIDENT (Prices, RESEED, 0)");
//Roll the identity forward till it finds the last used number.
context.Database.ExecuteSqlCommand("DBCC CHECKIDENT (Prices, RESEED)");
for (int i = 0; i < newElements.Total; i++)
{
var newPrice = new Price()
{
Date = newElements.From.AddDays(i),
PriceFrom = newElements.Price,
TotalNights = newElements.TotalNights,
Profit = newElements.Profit
};
context.AddToPrices(newPrice);
}
context.SaveChanges();
}
编辑:
这是一个只使用SqlCommand执行它的版本,并且不依赖于Entity Framework。
using (var connection = new SqlConnection(_connectionString))
{
connection.Open();
using (SqlTransaction trans = connection.BeginTransaction("PricesCleanup"))
using (var command = new SqlCommand("", connection, trans))
{
//Reseed the identity to 0.
command.CommandText = "DBCC CHECKIDENT (Prices, RESEED, 0)";
command.ExecuteNonQuery();
//Roll the identity forward till it finds the last used number.
command.CommandText = "DBCC CHECKIDENT (Prices, RESEED)";
command.ExecuteNonQuery();
trans.Commit();
}
}