实体框架和sql身份问题

时间:2015-08-07 16:36:43

标签: c# asp.net sql-server entity-framework uniqueidentifier

我需要重置我的表的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();
}

2 个答案:

答案 0 :(得分:1)

不要在EF中单独循环并删除价格,而只需使用ExecuteSqlCommandTRUNCATE表格。

这两者都会清空它(比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();
    }
}