How to RESEED LocalDB Table using Entity Framework?

c# entity-framework localdb sql tsql


Is There any way to RESEED a LocalDB Table using EF?

I'd prefer not to use this SQL Command :


FYI : I'm using EF 6.1.

Thanks alot.

10/2/2014 7:04:58 AM

Accepted Answer

I assume you're trying to reset the primary key on the table? If so, no there is no way in EF to do this.

As you stated, you would have to use a SQL command such as:

context.Database.ExecuteSqlCommand("DBCC CHECKIDENT('TableName', RESEED, 0)")

But I have to ask why you're trying to do this anyway? It shouldn't matter to you what value is in your primary key field.

10/10/2014 8:33:52 AM

Popular Answer

With the help of Rui Jarimba's nice answer, it's better to write an extension method like below if you need DBCC CHECKIDENT everywhere:

public static class ContextExtensions
    public static void DbccCheckIdent<T>(this DbContext context, int? reseedTo = null) where T : class
            $"DBCC CHECKIDENT('{context.GetTableName<T>()}',RESEED{(reseedTo != null ? "," + reseedTo: "")});" +
            $"DBCC CHECKIDENT('{context.GetTableName<T>()}',RESEED);");

    public static string GetTableName<T>(this DbContext context) where T : class
        var objectContext = ((IObjectContextAdapter) context).ObjectContext;
        return objectContext.GetTableName<T>();

    public static string GetTableName<T>(this ObjectContext context) where T : class
        var sql = context.CreateObjectSet<T>().ToTraceString();
        var regex = new Regex(@"FROM\s+(?<table>.+)\s+AS");
        var match = regex.Match(sql);
        var table = match.Groups["table"].Value;
        return table;

And enjoy simple call to it:

using (var db = new LibraryEntities())
    db.DbccCheckIdent<Book>(); //which Book is one of your entities
    db.DbccCheckIdent<Book>(0); //if you want to pass a new seed

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow