ef core set identity_insert off code example
Example: ef core set identity_insert off
#region IDENTITY_INSERT
public static void EnableIdentityInsert(this DbContext context) => SetIdentityInsert(context, true);
public static void DisableIdentityInsert(this DbContext context) => SetIdentityInsert(context, false);
private static void SetIdentityInsert([NotNull] DbContext context, bool enable)
{
if (context == null) throw new ArgumentNullException(nameof(context));
var entityType = context.Model.FindEntityType(typeof(T));
var value = enable ? "ON" : "OFF";
context.Database.ExecuteSqlRaw($"SET IDENTITY_INSERT {entityType.GetSchema()}.{entityType.GetTableName()} {value}");
}
public static void SaveChangesWithIdentityInsert([NotNull] this DbContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
using var transaction = context.Database.BeginTransaction();
context.EnableIdentityInsert();
context.SaveChanges();
context.DisableIdentityInsert();
transaction.Commit();
}
#endregion
#region IDENTITY_INSERT ASYNC
public static async Task EnableIdentityInsertAsync(this DbContext context) => await SetIdentityInsertAsync(context, true);
public static async Task DisableIdentityInsertAsync(this DbContext context) => await SetIdentityInsertAsync(context, false);
private static async Task SetIdentityInsertAsync([NotNull] DbContext context, bool enable)
{
if (context == null) throw new ArgumentNullException(nameof(context));
var entityType = context.Model.FindEntityType(typeof(T));
var value = enable ? "ON" : "OFF";
await context.Database.ExecuteSqlRawAsync($"SET IDENTITY_INSERT {entityType.GetSchema()}.{entityType.GetTableName()} {value}");
}
public static async Task SaveChangesWithIdentityInsertAsync([NotNull] this DbContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
await using var transaction = await context.Database.BeginTransactionAsync();
await context.EnableIdentityInsertAsync();
await context.SaveChangesAsync();
await context.EnableIdentityInsertAsync();
await transaction.CommitAsync();
}
#endregion