How to RESEED LocalDB Table using Entity Framework

2019-04-04 23:19发布

问题:

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

I'd prefer not to use this SQL Command :

DBCC CHECKIDENT('TableName', RESEED, 0)

FYI : I'm using EF 6.1.

Thanks alot.

回答1:

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.



回答2:

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
    {
        context.Database.ExecuteSqlCommand(
            $"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
}